Module: ActsAsLookupHasLookupClassMethods
- Defined in:
- lib/acts_as_lookup.rb
Instance Method Summary collapse
-
#force_class_load(cname) ⇒ Object
separate the logic for forcing a class load to isolate it, as well as making testing easier —————————————————————————.
-
#has_lookup(association_name, options = {}) ⇒ Object
create an association from the current rails model to a lookup model, providing a name for the association (default will assume the association name follows rails association naming conventions).
Instance Method Details
#force_class_load(cname) ⇒ Object
separate the logic for forcing a class load to isolate it, as well as making testing easier
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'lib/acts_as_lookup.rb', line 245 def force_class_load(cname) # this is a hack that is not at all pretty but seems to get around the # double-class loading problems that arise in rails: see for example # https://rails.lighthouseapp.com/projects/8994/tickets/1339 # it may create other problems though, so be careful.... rails_root = nil begin rails_root = Rails.root rescue end # fallback for Rails 2 rails_root ||= RAILS_ROOT if defined?(RAILS_ROOT) if !Object.const_defined?(cname) require File.join(rails_root, 'app', 'models', cname.underscore) end end |
#has_lookup(association_name, options = {}) ⇒ Object
create an association from the current rails model to a lookup model, providing a name for the association (default will assume the association name follows rails association naming conventions).
options:
:class_name: override the default assumption of class name from
+assocaition_name+ argument and explicitly pass in the
classname (in CamelCase) for the association.
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/acts_as_lookup.rb', line 217 def has_lookup(association_name, = {}) cname = [:class_name] || association_name.to_s.camelize force_class_load cname # this is inspired/borrowed from Rapleaf's has_rap_enum klass = Kernel.const_get(cname) unless(klass && klass.is_a?(ActsAsLookupClassMethods)) raise "#{cname.to_s.camelize} is not an acts_as_lookup class" end # create the reader method for the lookup association define_method(association_name) do klass.lookup_by_id(send("#{association_name}_id")) end # create the writer method for the lookup association define_method("#{association_name}=") do |assoc| unless (assoc.class.name == klass.name) || assoc.nil? raise "Argument not of type #{klass.name}" end send("#{association_name}_id=", assoc && assoc.id) end end |