Class: Cranky::Job

Inherits:
Object
  • Object
show all
Defined in:
lib/cranky/job.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target, overrides = {}) ⇒ Job

Returns a new instance of Job.



7
8
9
10
11
12
# File 'lib/cranky/job.rb', line 7

def initialize(target, overrides={})
  @defaults = {}
  @target = target
  @overrides = overrides
  @return_attributes = overrides.delete(:_return_attributes)
end

Instance Attribute Details

#defaults=(defs) ⇒ Object (writeonly)

Sets the attribute defaults

Parameters:

  • value

    the value to set the attribute defaults to.



4
5
6
# File 'lib/cranky/job.rb', line 4

def defaults=(value)
  @defaults = value
end

#overridesObject (readonly)

Returns the value of attribute overrides.



5
6
7
# File 'lib/cranky/job.rb', line 5

def overrides
  @overrides
end

#return_attributesObject (readonly)

Returns the value of attribute return_attributes.



5
6
7
# File 'lib/cranky/job.rb', line 5

def return_attributes
  @return_attributes
end

Instance Method Details

#assign(attribute, value) ⇒ Object

Assign the value to the given attribute of the item



34
35
36
37
38
39
40
41
42
# File 'lib/cranky/job.rb', line 34

def assign(attribute, value)
  unless value == :skip || attribute == :class
    if item.respond_to?("#{attribute}=")
      item.send("#{attribute}=", value)
    elsif item.is_a?(Hash)
      item[attribute] = value
    end
  end
end

#attributesObject



14
15
16
# File 'lib/cranky/job.rb', line 14

def attributes
  @attributes ||= @defaults.merge(@overrides)
end

#executeObject



44
45
46
47
48
49
50
51
52
# File 'lib/cranky/job.rb', line 44

def execute
  values = attributes.reject { |attribute, value| value.respond_to?("call") }
  blocks = attributes.select { |attribute, value| value.respond_to?("call") }

  values.each { |attribute, value| assign(attribute, value) }
  blocks.each { |attribute, value| assign(attribute, value.call(*(value.arity > 0 ? [item] : []))) }

  item
end

#itemObject

Returns the created item



24
25
26
27
28
29
30
31
# File 'lib/cranky/job.rb', line 24

def item
  return @item if @item
  if @return_attributes
    @item = Hash.new
  else
    @item = get_constant(attributes[:class] ? attributes.delete(:class) : @target).new
  end
end