Module: AttrExtras::ClassMethods

Included in:
Class
Defined in:
lib/attr_extras.rb

Instance Method Summary collapse

Instance Method Details

#attr_id_query(*names) ⇒ Object


77
78
79
# File 'lib/attr_extras.rb', line 77

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


73
74
75
# File 'lib/attr_extras.rb', line 73

def attr_query(*names)
  attr_query_with_suffix(*names, "")
end

#attr_value(*names) ⇒ Object


55
56
57
58
59
60
61
62
63
# File 'lib/attr_extras.rb', line 55

def attr_value(*names)
  attr_reader *names

  define_method(:==) do |other|
    return false unless other.is_a?(self.class)

    names.all? { |attr| self.public_send(attr) == other.public_send(attr) }
  end
end

#method_object(method_name, *names) ⇒ Object


65
66
67
68
69
70
71
# File 'lib/attr_extras.rb', line 65

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

#vattr_initialize(*names) ⇒ Object


50
51
52
53
# File 'lib/attr_extras.rb', line 50

def vattr_initialize(*names)
  attr_initialize(*names)
  attr_value *attr_flat_names(names)
end