Module: AttrExtras::ClassMethods
- Included in:
- Class
- Defined in:
- lib/attr_extras.rb
Instance Method Summary collapse
- #attr_id_query(*names) ⇒ Object
- #attr_initialize(*names) ⇒ Object
- #attr_private(*names) ⇒ Object
- #attr_query(*names) ⇒ Object
- #attr_value(*names) ⇒ Object
- #method_object(method_name, *names) ⇒ Object
- #pattr_initialize(*names) ⇒ Object
Instance Method Details
#attr_id_query(*names) ⇒ Object
75 76 77 |
# File 'lib/attr_extras.rb', line 75 def attr_id_query(*names) attr_query_with_suffix(*names, "_id") end |
#attr_initialize(*names) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/attr_extras.rb', line 5 def attr_initialize(*names) min_arity = names.count { |n| not n.is_a?(Array) } max_arity = names.length define_method(:initialize) do |*values| provided_arity = values.length unless (min_arity..max_arity).include?(provided_arity) arity_range = [min_arity, max_arity].uniq.join("..") raise ArgumentError, "wrong number of arguments (#{provided_arity} for #{arity_range})" end names.zip(values).each do |name_or_names, value| if name_or_names.is_a?(Array) value ||= {} name_or_names.each do |name| if name.to_s.end_with?("!") actual_name = name.to_s.chop.to_sym actual_value = value.fetch(actual_name) else actual_name = name actual_value = value[name] end instance_variable_set("@#{actual_name}", actual_value) end else name = name_or_names instance_variable_set("@#{name}", value) end end end end |
#attr_private(*names) ⇒ Object
40 41 42 43 |
# File 'lib/attr_extras.rb', line 40 def attr_private(*names) attr_reader(*names) private(*names) end |
#attr_query(*names) ⇒ Object
71 72 73 |
# File 'lib/attr_extras.rb', line 71 def attr_query(*names) attr_query_with_suffix(*names, "") end |
#attr_value(*names) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/attr_extras.rb', line 50 def attr_value(*names) attr_initialize(*names) flat_names = attr_flat_names(names) attr_reader *flat_names define_method(:==) do |other| return false unless other.is_a?(self.class) flat_names.all? { |attr| self.public_send(attr) == other.public_send(attr) } end end |
#method_object(method_name, *names) ⇒ Object
63 64 65 66 67 68 69 |
# File 'lib/attr_extras.rb', line 63 def method_object(method_name, *names) singleton_class.send(:define_method, method_name) do |*values| new(*values).send(method_name) end pattr_initialize(*names) end |
#pattr_initialize(*names) ⇒ Object
45 46 47 48 |
# File 'lib/attr_extras.rb', line 45 def pattr_initialize(*names) attr_initialize(*names) attr_private *attr_flat_names(names) end |