Module: Institutions::Util
- Included in:
- Institution
- Defined in:
- lib/institutions/institution/util.rb
Overview
:no_doc
Instance Method Summary collapse
-
#hash_keyize(s) ⇒ Object
Convert s to a hash key.
-
#method_missing(method, *args, &block) ⇒ Object
Dynamically sets attr_readers for elements.
-
#respond_to_missing?(method, include_private = false) ⇒ Boolean
Tells users that we respond to missing methods if they are instance variables.
-
#to_hash ⇒ Object
Converts the Institution to a hash with keys representing each Institutional attribute (as symbols) and their corresponding values.
- #valid_instance_variable?(id) ⇒ Boolean
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
Dynamically sets attr_readers for elements
23 24 25 26 27 28 29 30 31 |
# File 'lib/institutions/institution/util.rb', line 23 def method_missing(method, *args, &block) instance_variable = instance_variablize(method) if respond_to_missing?(method) and instance_variable_defined?(instance_variable) self.class.send :attr_reader, method.to_sym instance_variable_get instance_variable else super end end |
Instance Method Details
#hash_keyize(s) ⇒ Object
Convert s to a hash key
59 60 61 62 |
# File 'lib/institutions/institution/util.rb', line 59 def hash_keyize(s) # Remove beginning '@' and convert to symbol for hash keys. s.to_s.sub(/^@/,'').to_sym end |
#respond_to_missing?(method, include_private = false) ⇒ Boolean
Tells users that we respond to missing methods if they are instance variables.
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/institutions/institution/util.rb', line 37 def respond_to_missing?(method, include_private = false) # Short circuit if we have invalid instance variable name, # otherwise we get an exception that we don't need. return super unless valid_instance_variable? method if instance_variable_defined? instance_variablize(method) true else super end end |
#to_hash ⇒ Object
Converts the Institution to a hash with keys representing each Institutional attribute (as symbols) and their corresponding values. Example:
require 'institutions'
institution = Institution.new("my_inst", "My Institution")
data.to_hash # => {:code => "my_inst", :name => "My Institution", :default => false }
12 13 14 15 16 17 18 |
# File 'lib/institutions/institution/util.rb', line 12 def to_hash hash = {} instance_variables.each do |inst_var| hash[hash_keyize(inst_var)] = instance_variable_get(inst_var) end hash end |
#valid_instance_variable?(id) ⇒ Boolean
48 49 50 |
# File 'lib/institutions/institution/util.rb', line 48 def valid_instance_variable?(id) id.to_sym.id2name.match(/[\@\=\?+\[\]]/).nil? end |