-
-
Save virtualstaticvoid/1014402 to your computer and use it in GitHub Desktop.
A model dumper for rails console ( Rails 3 or later ) and .irbrc for rails env
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- mode: ruby; coding: utf-8 -*- | |
if defined? Rails | |
railsrc = __FILE__ + '.rails' | |
load railsrc if File.exist? railsrc | |
envrc = File.join( Rails.root, '.irbrc' ) | |
load envrc if File.exist? envrc | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- mode: ruby -*- | |
IRB.conf[:PROMPT][:RAILS] = IRB.conf[:PROMPT][:DEFAULT].dup | |
IRB.conf[:PROMPT][:RAILS].merge!({ | |
:PROMPT_I => "#{Rails.env}(%m):%03n:%i> " | |
}) | |
IRB.conf[:PROMPT_MODE] = :RAILS | |
begin | |
require 'ya2yaml' | |
rescue LoadError | |
end | |
=begin | |
* Dump given model to YAML or CSV | |
* Place dumped file in #{Rails.root} | |
=end | |
class ModelDumper | |
class << self | |
if ( defined? Ya2YAML ) | |
def to_yaml( obj ) | |
obj.ya2yaml | |
end | |
else | |
def to_yaml( obj ) | |
obj.to_yaml | |
end | |
end | |
def dump( model, format = 'yaml' ) | |
if ( model.respond_to? :model_name and model.respond_to? :model_fields ) | |
if ( methods.grep( /\Adump_to_#{format}\z/ ).size > 0 ) | |
send( "dump_to_#{format}", model ) | |
else | |
STDERR.puts "#{format} is not supported." | |
end | |
else | |
STDERR.puts "#{model.class} is not Model." | |
end | |
end | |
def dump_to_csv( model ) | |
FasterCSV.open( filename( model, 'csv' ), 'w' ) do |csv| | |
fields = model.model_fields.keys | |
csv << fields.map { |e| e.to_s } | |
model.all.each { |e| | |
csv << fields.map { |key| convert_bool( e[key] ) } | |
} | |
end | |
end | |
def dump_to_yaml( model ) | |
open( filename( model, 'yml' ), 'w' ) do |f| | |
key = 0 | |
f.puts model.all.map { |e| | |
key += 1 | |
to_yaml( key => convert_bool( e.attributes ) ).sub( /\A--- \n/, '' ) | |
} | |
end | |
end | |
alias_method :dump_to_yml, :dump_to_yaml | |
def filename( model, suffix ) | |
"#{model.table_name}.#{suffix}" | |
end | |
def convert_bool( val ) | |
case val | |
when true | |
't' | |
when false | |
'f' | |
when Hash | |
Hash[*val.map { |k, v| | |
[k, convert_bool(v)] | |
}.flatten] | |
else | |
val | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment