Module: Miasma::Utils::Lazy::InstanceMethods

Defined in:
lib/miasma/utils/lazy.rb

Overview

Instance methods for laziness

Instance Method Summary collapse

Instance Method Details

#attributesSmash

Returns current data state.

Returns:

  • (Smash)

    current data state



29
30
31
# File 'lib/miasma/utils/lazy.rb', line 29

def attributes
  data.merge(dirty)
end

#dataSmash

Returns argument hash.

Returns:

  • (Smash)

    argument hash



13
14
15
16
17
18
# File 'lib/miasma/utils/lazy.rb', line 13

def data
  unless(@data)
    @data = Smash.new
  end
  @data
end

#dirtySmash

Returns updated data.

Returns:

  • (Smash)

    updated data



21
22
23
24
25
26
# File 'lib/miasma/utils/lazy.rb', line 21

def dirty
  unless(@dirty)
    @dirty = Smash.new
  end
  @dirty
end

#dirty?(attr = nil) ⇒ TrueClass, FalseClass

Model is dirty or specific attribute is dirty

Parameters:

  • attr (String, Symbol) (defaults to: nil)

    name of attribute

Returns:

  • (TrueClass, FalseClass)

    model or attribute is dirty



73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/miasma/utils/lazy.rb', line 73

def dirty?(attr=nil)
  if(attr)
    dirty.has_key?(attr)
  else
    if(@_checksum)
      !dirty.empty? ||
        @_checksum != Digest::SHA256.hexdigest(MultiJson.dump(data))
    else
      true
    end
  end
end

#inspectString

Returns:

  • (String)


92
93
94
# File 'lib/miasma/utils/lazy.rb', line 92

def inspect
  "<#{self.class.name}:#{object_id} [#{data.inspect}]>"
end

#load_data(args = {}) ⇒ self

Create new instance

Parameters:

  • args (Hash) (defaults to: {})

Returns:

  • (self)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/miasma/utils/lazy.rb', line 37

def load_data(args={})
  args = args.to_smash
  @data = Smash.new
  self.class.attributes.each do |name, options|
    val = args[name]
    if(options[:required] && !args.has_key?(name) && !options.has_key?(:default))
      raise ArgumentError.new("Missing required option: `#{name}`")
    end
    if(val.nil? && !args.has_key?(name) && options[:default])
      if(options[:default])
        val = options[:default].respond_to?(:call) ? options[:default].call : options[:default]
      end
    end
    if(args.has_key?(name) || val)
      self.send("#{name}=", val)
    end
  end
  self
end

#to_sString

Returns:

  • (String)


87
88
89
# File 'lib/miasma/utils/lazy.rb', line 87

def to_s
  "<#{self.class.name}:#{object_id}>"
end

#valid_stateself

Identifies valid state and automatically merges dirty attributes into data, clears dirty attributes

Returns:

  • (self)


62
63
64
65
66
67
# File 'lib/miasma/utils/lazy.rb', line 62

def valid_state
  data.merge!(dirty)
  dirty.clear
  @_checksum = Digest::SHA256.hexdigest(MultiJson.dump(data))
  self
end