ActsAsCSVable v1.0
Monday, September 15th, 2008It’s finally here: ActsAsCSVable!
Important Update! on June 25th, 2009
ActsAsCSVable is now on GitHub.com and all development has moved to git.
http://github.com/pjleonhardt/ActsAsCSVable/tree/master
Git Repository: git://github.com/pjleonhardt/ActsAsCSVable.git
History
I developed a plugin while working as a Rails Developer, CSVExportable, which was originally based off of some code from Bryan Helmkamp.
CSVExportable was good, but it was an evolutionary design. As such, it was hodgepodged together with no since of organization. I decided to rewrite the plugin from scratch, and design it a little bit better this time around (since I knew where I would end up this time around). It also needed a name change, since it does both CSV exporting and importing. I’ve seen a few Rails plugins that will do CSV exporting, but I haven’t found one that does both, or even importing. Importing is definitely tricky, but I think that if you follow a few guidelines, it can be useful in the right situations.
Installation
Subversion: Trunk | Stable v1.0 | Development Application
Project Management: Redmine
Usage
#in your model
acts_as_csv_exportable :fancy_naming, [{:first => "first_name"}, {:last => "last_name"}, {:email => "email_address"}, {:address => "mailing_address"}]
acts_as_csv_exportable :detailed, [:first_name, :last_name, :email_address, :mailing_address, :formatted_date]
acts_as_csv_exportable :default, [:id, :first_name, :last_name]
acts_as_csv_importable :default, [:id, :first_name, :last_name]
acts_as_csv_importable :new_projects, [:name, :details, :\owner_username]
def formatted_date
self.date.strftime("%Y/%M/%D")
end
def owner_username=(username)
self.owner = Users.find_by_username(username)
end
# your contrller
def index
@people = Person.find(:all)
respond_to do |wants|
wants.csv { render :text => @people.to_csv(:columns => [:first_name, :last_name, :date_of_birth]) }
# or
wants.csv { render :text => @people.to_csv(:template => :fancy) }
# or
wants.csv { render :text => @peope.to_csv } #renders the :default template
end
end
#/people/import
def import
file = params[:csv_uplodad]
template = params[:upload_template]
projects = Project.from_csv(file, template)
if projects.all?(&:valid?)
projects.each(&:save)
else
# Options options options...
# 1) Save valid rows, and re-export invalid rows
# 2) Save nothing, and tell user which rows were invalid
# 3) Save nothing and tell them rows are invalid
# 4) Up to you!
end
end
I only ask that if you use the plugin, let me know! I love to keep track of how its being used. The more response, the more likely I am to improve it and write more plugins! Leave a message below, or send me an email. I’d love to hear your thoughts for improvement, as well.