Class: Change

Inherits:
Object show all
Defined in:
lib/taco/change.rb

Overview

FIXME: put this in a namespace

Defined Under Namespace

Classes: Invalid

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Change

Returns a new instance of Change.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/taco/change.rb', line 13

def initialize(args={})
  args.each do |attr, value|
    raise ArgumentError.new("Unknown attribute #{attr}") unless self.respond_to?(attr)

    case attr.to_sym
    when :created_at
      value = Time.parse(value) unless value.is_a?(Time)
    when :attribute
      value = value.to_sym
    end

    instance_variable_set("@#{attr.to_s}", value)
  end

  @created_at = Time.parse(@created_at) if @created_at.is_a?(String)
  @created_at = timescrub(@created_at || Time.now)

  self
end

Instance Attribute Details

#attributeObject

Returns the value of attribute attribute.



9
10
11
# File 'lib/taco/change.rb', line 9

def attribute
  @attribute
end

#created_atObject (readonly)

Returns the value of attribute created_at.



8
9
10
# File 'lib/taco/change.rb', line 8

def created_at
  @created_at
end

#new_valueObject

Returns the value of attribute new_value.



11
12
13
# File 'lib/taco/change.rb', line 11

def new_value
  @new_value
end

#old_valueObject

Returns the value of attribute old_value.



10
11
12
# File 'lib/taco/change.rb', line 10

def old_value
  @old_value
end

Class Method Details

.from_json(the_json) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/taco/change.rb', line 33

def self.from_json(the_json)
  begin
    hash = JSON.parse(the_json)
  rescue JSON::ParserError => e
    raise Change::Invalid.new(e.to_s)
  end

  Change.new(hash)
end

Instance Method Details

#to_json(state = nil) ⇒ Object



51
52
53
54
55
# File 'lib/taco/change.rb', line 51

def to_json(state=nil)
  valid? :raise => true
  hash = { :created_at => created_at, :attribute => attribute, :old_value => old_value, :new_value => new_value }
  JSON.pretty_generate(hash)
end

#to_s(opts = {}) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/taco/change.rb', line 57

def to_s(opts={})
  if opts[:simple]
    "#{attribute} : #{old_value} => #{new_value}"
  else
    fields = [ date(created_at), attribute, old_value || '[nil]', new_value ]
    "%10s : %12s : %s => %s" % fields
  end
end

#valid?(opts = {}) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



43
44
45
46
47
48
49
# File 'lib/taco/change.rb', line 43

def valid?(opts={})
  # old_value is optional!
  #
  valid = created_at && attribute && new_value
  raise Invalid if opts[:raise] && !valid
  valid
end