class Fixturator::Generator

Attributes

excluded_attributes[R]
model[R]

Public Class Methods

new(model, excluded_attributes: []) click to toggle source
# File lib/fixturator/generator.rb, line 5
def initialize(model, excluded_attributes: [])
  @model = model
  @excluded_attributes = excluded_attributes
end

Public Instance Methods

call() click to toggle source
# File lib/fixturator/generator.rb, line 10
def call
  with_fixture_file do |file|
    model.find_each.with_index do |record, index|
      file.puts(fixturize(record, index + 1))
    end
  end
end

Private Instance Methods

attributes_for(record) click to toggle source
# File lib/fixturator/generator.rb, line 40
def attributes_for(record)
  record.
    attributes.
    compact.
    tap(&method(:replace_times)).
    except(*excluded_attributes)
end
fixture_path() click to toggle source
# File lib/fixturator/generator.rb, line 57
def fixture_path
  if Rails::VERSION::MAJOR > 5
    ActiveSupport::TestCase.fixture_path
  else
    Rails.root.join("test", "fixtures", model_lower_name.pluralize + ".yml")
  end
end
fixturize(record, index) click to toggle source
# File lib/fixturator/generator.rb, line 26
def fixturize(record, index)
  to_yaml(
    "#{model_lower_name}_#{index}" => attributes_for(record)
  )
end
model_lower_name() click to toggle source
# File lib/fixturator/generator.rb, line 65
def model_lower_name
  model.name.underscore.gsub("/", "_")
end
remove_yaml_header(yaml) click to toggle source
# File lib/fixturator/generator.rb, line 36
def remove_yaml_header(yaml)
  yaml.sub(/\A---\n/, "")
end
replace_times(attributes) click to toggle source
# File lib/fixturator/generator.rb, line 48
def replace_times(attributes)
  attributes["created_at"] = static_time if attributes["created_at"]
  attributes["updated_at"] = static_time if attributes["updated_at"]
end
static_time() click to toggle source
# File lib/fixturator/generator.rb, line 53
def static_time
  Time.parse("2016-10-10").utc
end
to_yaml(hash) click to toggle source
# File lib/fixturator/generator.rb, line 32
def to_yaml(hash)
  remove_yaml_header(hash.to_yaml) + "\n"
end
with_fixture_file(&block) click to toggle source
# File lib/fixturator/generator.rb, line 22
def with_fixture_file(&block)
  File.open(fixture_path, "w", &block)
end