Module: Hopsoft::ActsAsLookup::ClassMethods

Defined in:
lib/hopsoft/acts_as_lookup.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_lookup(options = {}) ⇒ Object

Adds lookup table behavior to a model.



61
62
63
64
65
66
# File 'lib/hopsoft/acts_as_lookup.rb', line 61

def acts_as_lookup(options={})
  @key_column = options[:key_column] || :name
  include Hopsoft::ActsAsLookup::IsLookup::InstanceMethods
  extend Hopsoft::ActsAsLookup::IsLookup::StaticMethods
  init
end

#belongs_to(association_id, options = {}) ⇒ Object

Used to implicitly mixin additional behavior for models that contain “belongs_to” relationships to lookup tables.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/hopsoft/acts_as_lookup.rb', line 70

def belongs_to(association_id, options={})
  result = super

  begin
    parent_model_name = options[:class_name] || association_id.to_s.camelize
    parent_model = Object.const_get(parent_model_name)
    parent_acts_as_lookup = defined?(parent_model.key_column)

    # only add the behavior for belongs_to relationships where the parent implements "acts_as_lookup".
    if parent_acts_as_lookup
      @lookup_models ||= []
      @lookup_models << parent_model

      unless @lookup_behavior_added
        include Hopsoft::ActsAsLookup::UsesLookups::InstanceMethods
        extend Hopsoft::ActsAsLookup::UsesLookups::StaticMethods
        @lookup_behavior_added = true
      end
    end
  rescue
    puts("LookupTables plugin error!  Unable to override belongs_to for '#{parent_model_name}'!\n#{$!}")
  end

  result
end