Module: DealsWith::ActionController::ClassMethods

Defined in:
lib/deals_with/action_controller/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#deals_with(model_name, options = {}, &scope_proc) ⇒ Object



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
# File 'lib/deals_with/action_controller/class_methods.rb', line 11

def deals_with(model_name, options={}, &scope_proc)
  tmp_model_name = model_name.to_s.classify
  model_class = nil
  begin
    model_class = tmp_model_name.constantize
  rescue
    tmp_model_name = model_name.to_s.camelize
    model_class = (tmp_model_name.constantize rescue nil)
  end
  model_name = tmp_model_name
  
  unless deals_with_models[model_name]
    
    if model_class
      model_class.reflect_on_all_associations(:belongs_to).each do |reflection|
        deals_with(reflection.class_name)
      end
    end
    
    deals_with_models[model_name] = DealsWith::Resource.new(self, 
      model_name, options, &scope_proc)
    
    generate_resource_methods(model_name)
  end
end

#deals_with_modelsObject



7
8
9
# File 'lib/deals_with/action_controller/class_methods.rb', line 7

def deals_with_models
  @deals_with_models ||= {}
end

#generate_resource_methods(model_name) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/deals_with/action_controller/class_methods.rb', line 38

def generate_resource_methods(model_name)
  short_name = model_name.gsub(/.+[:]{2}/, '')
  class_eval %{
    def #{short_name.pluralize.underscore}
      @#{short_name.pluralize.underscore} ||=
        self.class.deals_with_models[#{model_name.inspect}].all(self)
    end
    def #{short_name.underscore}
      @#{short_name.underscore} ||=
        self.class.deals_with_models[#{model_name.inspect}].find(self)
    end
    def build_#{short_name.underscore}
      @#{short_name.underscore} ||=
        self.class.deals_with_models[#{model_name.inspect}].build(self)
    end
  }
end