Module: Sohm::Utils
- Defined in:
- lib/sohm.rb
Overview
Instead of monkey patching Kernel or trying to be clever, it’s best to confine all the helper methods in a Utils module.
Class Method Summary collapse
-
.const(context, name) ⇒ Object
Used by: ‘attribute`, `counter`, `set`, `reference`, `collection`.
- .dict(arr) ⇒ Object
Class Method Details
.const(context, name) ⇒ Object
Used by: ‘attribute`, `counter`, `set`, `reference`, `collection`.
Employed as a solution to avoid ‘NameError` problems when trying to load models referring to other models not yet loaded.
Example:
class Comment < Sohm::Model
reference :user, User # NameError undefined constant User.
end
# Instead of relying on some clever `const_missing` hack, we can
# simply use a symbol or a string.
class Comment < Sohm::Model
reference :user, :User
reference :post, "Post"
end
68 69 70 71 72 73 74 75 76 77 |
# File 'lib/sohm.rb', line 68 def self.const(context, name) case name when Symbol, String # In JRuby, Module::const_get can not work on nested symbols # such as "Foo::Bar", so we have to do it piece by piece here pieces = name.to_s.split("::") pieces.reduce(context) { |context, piece| context.const_get(piece) } else name end end |
.dict(arr) ⇒ Object
79 80 81 |
# File 'lib/sohm.rb', line 79 def self.dict(arr) Hash[*arr] end |