Module: Selections::Selectable::ModelMixin::ClassMethods
- Defined in:
- lib/selections/selectable.rb
Instance Method Summary collapse
-
#label_to_id(label) ⇒ Object
label_to_id.
-
#method_missing(lookup_code, *options) ⇒ Object
Dynamic Lookups.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(lookup_code, *options) ⇒ Object
Dynamic Lookups
Assuming there is a list with the following system_codes
example of a nested list of system codes:
-
priority
-
high
-
-
medium
-
-
low
-
Selection.priority => return priority instance
Selection.priorities => returns [high, medium, low] instances (children)
44 45 46 47 48 49 50 51 52 |
# File 'lib/selections/selectable.rb', line 44 def method_missing lookup_code, * if (scope = where(system_code: lookup_code.to_s)).exists? scope.first elsif (scope = where(system_code: lookup_code.to_s.singularize)).exists? scope.first.children else super end end |
Instance Method Details
#label_to_id(label) ⇒ Object
label_to_id
When using fixtures with the label same as the system_code, use this method to return the ID of the of the fixture and use this in Factories instead of using a lookup as it does not need a DB search.
eg: Fixture File
priority_high:
name: Priorities
system_code: priority_high
parent: priority
in Factory
priority: { Selection.priority_high } <== Don’t do this as it will need a DB lookup
priority_id: { Selection.label_to_id(:priority_high) } <== This will be much quicker
74 75 76 77 78 79 80 81 82 |
# File 'lib/selections/selectable.rb', line 74 def label_to_id(label) # ActiveRecord::FixtureSet replaces ActiveRecord::Fixtures in Rails 4 # This helps to ensure backwards compatibility if ActiveRecord::VERSION::MAJOR >= 4 ActiveRecord::FixtureSet.identify(label) else ActiveRecord::Fixtures.identify(label) end end |