Skip to content

Instantly share code, notes, and snippets.

@kirylrb
Created April 22, 2019 11:16
Show Gist options
  • Save kirylrb/3393779f3963dfe29786b169cafc88b8 to your computer and use it in GitHub Desktop.
Save kirylrb/3393779f3963dfe29786b169cafc88b8 to your computer and use it in GitHub Desktop.
rails ActiveRecord model record to yml fixture method
class ActiveRecord::Base
def to_fixture
output = {}
model = self
attrs = model.attributes.compact
attrs.delete_if { |_k, v| v.nil? }
attrs.each do |key, value|
attrs[key] = value.to_time.utc if value.class == ActiveSupport::TimeWithZone
end
attrs = attrs.sort_by { |k, _v| k == 'id' ? '0' : k }.to_h
output["#{model.class}_#{model.id}"] = attrs
puts output.to_yaml
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment