Class: Inkit

Inherits:
Object
  • Object
show all
Defined in:
lib/cache.rb,
lib/inkit.rb

Defined Under Namespace

Classes: Cache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Inkit

Constructor



15
16
17
18
19
20
# File 'lib/inkit.rb', line 15

def initialize(options)
  raise 'Please provide your secret key!' unless options[:secret]
  @secret = options[:secret].to_s
  @token = options[:token].to_s
  @cache = Cache.new(@secret)
end

Instance Attribute Details

#secretObject (readonly)

Returns the value of attribute secret.



12
13
14
# File 'lib/inkit.rb', line 12

def secret
  @secret
end

#tokenObject (readonly)

Returns the value of attribute token.



12
13
14
# File 'lib/inkit.rb', line 12

def token
  @token
end

Instance Method Details

#digest(hash) ⇒ Object



22
23
24
# File 'lib/inkit.rb', line 22

def digest(hash)
  OpenSSL::HMAC::hexdigest("sha256", @secret, hash.to_query)
end

#haml(view, options = {}) ⇒ Object



52
53
54
# File 'lib/inkit.rb', line 52

def haml(view, options = {})
  render(view, options, 'haml')
end

#html(view, options = {}) ⇒ Object



48
49
50
# File 'lib/inkit.rb', line 48

def html(view, options = {})
  render(view, options)
end

#pull(view, type = 'haml') ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/inkit.rb', line 26

def pull(view,type = 'haml')
  data = {:view => view.to_s, :type => type, :timestamp => Time.now.rfc2822}
  data[:digest] = digest(data)
  data[:token] = @token
  uri = URI("http://inkit.org/api/document?"+data.to_query)
  req = ::Net::HTTP::Get.new uri.request_uri
  if @cache.cached? view+"."+type
    req['If-Modified-Since'] = @cache.cached_at view+"."+type
  end
  res = ::Net::HTTP.start(uri.host, uri.port) {|http|
    http.request(req)
  }
  if res.is_a?(::Net::HTTPSuccess)
    @cache[view+"."+type] = res.body
    return @cache[view+"."+type]
  end
  if res.is_a?(::Net::HTTPNotModified)
    return @cache[view+"."+type]
  end
  raise res.code
end

#render(view, options = {}, type = 'html') ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/inkit.rb', line 56

def render(view, options = {}, type = 'html')
  ret = self.pull(view,type)
  if options[:layout]
    layout = render(options[:layout], {}, type)
    indent = 0
    if layout =~ /( *)\{{3}yield\}{3}/
      indent = $1.length
    end
    ret = "\n#{ret}"
    ret = Mustache.render(layout,:yield => Mustache.render(ret.indent(indent)))
  end
  ret.gsub /\s*$/, ''
end