Module: Attribs::InstanceMethods

Defined in:
lib/attribs/instance_methods.rb

Instance Method Summary collapse

Instance Method Details

#append_to(type, *objects) ⇒ Object



11
12
13
# File 'lib/attribs/instance_methods.rb', line 11

def append_to(type, *objects)
  with(type => instance_variable_get("@#{type}") + objects)
end

#initialize(attributes = {}) ⇒ Object



3
4
5
# File 'lib/attribs/instance_methods.rb', line 3

def initialize(attributes = {})
  super(self.class.attributes.defaults.merge(attributes))
end

#ppObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/attribs/instance_methods.rb', line 22

def pp
  indent = ->(str) { str.lines.map {|l| "  #{l}"}.join }
  format = ->(val) do
    if val.respond_to?(:pp)
      val.pp
    elsif val.is_a? Time
      "Time.parse(\"#{val.inspect}\")"
    else
      val.inspect
    end
  end

  values   = to_h_compact

  fmt_attrs = values.map do |attr, value|
    fmt_val = case value
              when Array
                if value.inspect.length < 50
                  "[#{value.map(&format).join(", ")}]"
                else
                  "[\n#{indent[value.map(&format).join(",\n")]}\n]"
                end
              else
                format[value]
              end
    "#{attr}: #{fmt_val}"
  end

  fmt_attrs_str = fmt_attrs.join(", ")

  if fmt_attrs_str.length > 50
    fmt_attrs_str = fmt_attrs.join(",\n")
  end

  if fmt_attrs_str =~ /\n/
    fmt_attrs_str = "\n#{indent[fmt_attrs_str]}\n"
  end
  "#{self.class.name}.new(#{fmt_attrs_str})"
end

#to_h_compactObject



15
16
17
18
19
20
# File 'lib/attribs/instance_methods.rb', line 15

def to_h_compact
  defaults = self.class.attributes.defaults
  to_h.reject do |attr, value|
    value.equal?(defaults[attr])
  end
end

#with(attributes) ⇒ Object



7
8
9
# File 'lib/attribs/instance_methods.rb', line 7

def with(attributes)
  self.class.new(to_h.update(attributes))
end