Module: ExposeModel::ClassMethods

Defined in:
lib/expose_model/expose_model.rb

Instance Method Summary collapse

Instance Method Details

#expose_model(model = nil) ⇒ Object

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/expose_model/expose_model.rb', line 11

def expose_model(model = nil)
  raise ArgumentError.new('expose_model requires a model name') if model.nil?
  model = model.to_s
  models = model.pluralize
  class_name = model.camelize

  class_eval(
    <<-EOM
      helper_method :#{model}, :#{models}

      def #{models}
        @#{models} ||= #{class_name}.all
      end
      private :#{models}

      def #{model}
        @#{model} ||= if params[:id]
          #{class_name}.find params[:id]
        else
          #{class_name}.new params[:#{model}]
        end
      end
      private :#{model}
    EOM
  )
end