Method: Lev::Handler::ClassMethods#paramify

Defined in:
lib/lev/handler.rb

#paramify(group, options = {}, &block) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/lev/handler.rb', line 116

def paramify(group, options={}, &block)
  method_name = "#{group.to_s}_params"
  variable_sym = "@#{method_name}".to_sym

  # Generate the dynamic ActiveAttr class given
  # the paramify block; I think the caching of the class
  # in paramify_classes is only necessary to maintain
  # the name of the class set in the const_set statement

  if paramify_classes[group].nil?
    paramify_classes[group] = Class.new(Lev::Paramifier) do
      include ActiveAttr::Model
      cattr_accessor :group
    end
    paramify_classes[group].class_eval(&block)
    paramify_classes[group].group = group

    # Attach a name to this dynamic class
    const_set("#{group.to_s.capitalize}Paramifier", 
              paramify_classes[group])
  end

  # Define the "#{group}_params" method to get the paramifier 
  # instance wrapping the params
  define_method method_name.to_sym do
    if !instance_variable_get(variable_sym)
      instance_variable_set(variable_sym, 
                            self.class.paramify_classes[group].new(params[group]))
    end
    instance_variable_get(variable_sym)
  end

  # Keep track of the accessor for the params so we can check
  # errors in it later
  paramify_methods.push(method_name.to_sym)
end