Class: FixtureBuilder::Namer

Inherits:
Object
  • Object
show all
Includes:
Delegations::Configuration
Defined in:
lib/fixture_builder/namer.rb

Instance Method Summary collapse

Methods included from Delegations::Configuration

included

Constructor Details

#initialize(configuration) ⇒ Namer

Returns a new instance of Namer.



5
6
7
8
9
10
# File 'lib/fixture_builder/namer.rb', line 5

def initialize(configuration)
  @configuration = configuration
  @custom_names = {}
  @model_name_procs = {}
  @record_names = {}
end

Instance Method Details

#name(custom_name, *model_objects) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/fixture_builder/namer.rb', line 16

def name(custom_name, *model_objects)
  raise "Cannot name an object blank" unless custom_name.present?
  model_objects.each do |model_object|
    raise "Cannot name a blank object" unless model_object.present?
    key = [model_object.class.table_name, model_object.id]
    raise "Cannot set name for #{key.inspect} object twice" if @custom_names[key]
    @custom_names[key] = custom_name
    model_object
  end
end

#name_model_with(model_class, &block) ⇒ Object



12
13
14
# File 'lib/fixture_builder/namer.rb', line 12

def name_model_with(model_class, &block)
  @model_name_procs[model_class.table_name] = block
end

#populate_custom_names(created_fixtures) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/fixture_builder/namer.rb', line 27

def populate_custom_names(created_fixtures)
  # Rails 3.1+, create_fixtures returns an array of Fixtures objects
  if not created_fixtures.first.is_a? Array
    # merge all fixtures hashes
    created_fixtures = created_fixtures.inject({}) { |hash, fixtures| hash.merge(fixtures.fixtures) }
  end

  # Rails 3.0 and earlier, create_fixtures returns an array of tuples
  created_fixtures.each do |fixture|
    name = fixture[0]
    id = fixture[1]['id'].to_i
    table_name = fixture[1].model_class.table_name
    key = [table_name, id]
    @custom_names[key] = name
  end
end

#record_name(record_hash, table_name, row_index) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/fixture_builder/namer.rb', line 44

def record_name(record_hash, table_name, row_index)
  key = [table_name, record_hash['id'].to_i]
  name = case
           when name_proc = @model_name_procs[table_name]
             name_proc.call(record_hash, row_index.succ!)
           when custom = @custom_names[key]
             custom
           else
             inferred_record_name(record_hash, table_name, row_index)
         end
  @record_names[table_name] ||= []
  @record_names[table_name] << name
  name.to_s
end