Class: FixtureToFactory::FactoryWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/fixture_to_factory/factory_writer.rb

Class Method Summary collapse

Class Method Details

.attribute_to_factory_line(key, value) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/fixture_to_factory/factory_writer.rb', line 36

def attribute_to_factory_line(key, value)
  result = ''
  if key != 'id'
    result = "#{key} { "
    result += value_in_factory_format(value)
    result += " }"
  end
  result
end

.convert_yaml_hashes_to_factory_file(class_name, fixture_yaml_hash) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/fixture_to_factory/factory_writer.rb', line 24

def convert_yaml_hashes_to_factory_file(class_name, fixture_yaml_hash)
  output = "FactoryGirl.define do\n"
  fixture_yaml_hash.each do |fixture, values|
    output += "\n  factory :#{fixture}, class: #{class_name}\n"
    values.each do |key, value|
      output += "    #{attribute_to_factory_line(key, value)}\n"
    end
    output += "  end\n"
  end
  output += "\nend"
end

.value_in_factory_format(value) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/fixture_to_factory/factory_writer.rb', line 46

def value_in_factory_format(value)
  value_class = value.class
  case value_class.to_s
    when 'TrueClass'
      true
    when 'FalseClass'
      false
    when 'String'
      "%|#{value.gsub('|', '\|')}|"
    else
      "#{value}"
  end
end

.write_files(folder, file_hashes) ⇒ Object



3
4
5
6
7
# File 'lib/fixture_to_factory/factory_writer.rb', line 3

def self.write_files(folder, file_hashes)
  file_hashes.each do |fixture_path, fixtures|
    write_fixtures_to_file(folder, fixture_path, fixtures)
  end
end

.write_fixtures_to_file(folder, fixture_path, fixtures) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/fixture_to_factory/factory_writer.rb', line 12

def write_fixtures_to_file(folder, fixture_path, fixtures)
  fixture_file_name = fixture_path.split('/').last.split('.')[0..-2].join('.')
  class_name = ActiveSupport::Inflector.singularize(fixture_file_name).capitalize
  factory_file_name = "generated_#{fixture_file_name}.rb"

  puts "Writing #{fixture_file_name} fixtures to factory file #{factory_file_name}."

  FileUtils.mkdir_p(folder)
  file = File.new("#{folder}/#{factory_file_name}", 'w')
  file.write(convert_yaml_hashes_to_factory_file(class_name, fixtures))
end