Module: Wunderbar::Template

Defined in:
lib/wunderbar/sinatra.rb,
lib/wunderbar/script.rb

Overview

Tilt template implementation

Defined Under Namespace

Modules: Js, Json, Text Classes: Base, Html, Xhtml

Constant Summary collapse

PASSABLE =
[Numeric, String, Hash, Array]

Class Method Summary collapse

Class Method Details

.locals(scope, args) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/wunderbar/sinatra.rb', line 174

def self.locals(scope, args)
  args.push({}) if args.length == 1

  return unless Hash === args.last and not args.last[:locals]

  locals = {}

  scope.instance_variables.each do |ivar|
    next if [:@env, :@params].include? ivar
    value = scope.instance_variable_get(ivar)
    next unless PASSABLE.find {|klass| klass === value}
    locals[ivar] = value
  end

  args.last[:locals] = locals
end

.register(language, base = Base) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/wunderbar/sinatra.rb', line 191

def self.register(language, base=Base)
  template = Class.new(Template::Base) do 
    self.default_mime_type = language.mime
    include language
  end

  Array(language.ext).each do |ext|
    SinatraHelpers.send :define_method, ext do |*args, &block|
      # parse json
      if env['CONTENT_TYPE'] =~ /^\w+\/json/
        json = JSON.parse(env['rack.input'].read)
        @params.merge! json if Hash === json
      end

      Wunderbar::Template.locals(self, args)
      if Hash === args.last and args.last[:locals]
        @params.each do |name, value| 
          args.last[:locals]["@#{name}".to_sym] = value
        end
      end

      # text, json shortcuts
      if block == nil and args.length >= 1
        case args.first
        when Array, Hash
          block = proc { _! args.first } if ext == :_json
        when String
          block = proc { _ args.first } if ext == :_text
        end
      end

      template.evaluate(ext, self, *args, &block)
    end

    Tilt.register ext.to_s, template
  end
end