Monday, February 16, 2009

Code Generation using Rails, Rake and ERB

Two great things about Ruby are it's brevity and it's dynamic nature. A great way to introduce Ruby to a project written in another language is some simple code generation.

Say we need some XML files that represent data currently stored in a database. To make it simple, our desired file will use the table name pluralized as the parent element, and contain nested singular elements, one for each record in the database. Within the record elements, each field name is an element, and the value of that field is the text value of that element.

<?xml version="1.0" encoding="UTF-8"?>
<bonds xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="bonds.xsd">
<bond>
<issuer>GENERAL MOTORS CORP</issuer>
<rate>0.072</rate>
<coupon>Fixed</coupon>
<maturity>1/15/2011</maturity>
<type>US Corporate Debentures</type>
<price>19.5</price>
<yield>1.29582</yield>
<callable>true</callable>
<frequency>Semi-Annual</frequency>
<first_payment>7/15/2001</first_payment>
</bond>
<bond>
<issuer>FEDERAL NATL MTG ASSN</issuer>
<rate>0.045</rate>
<coupon>Variable</coupon>
<maturity>2/17/2012</maturity>
<type>US Agency Retail Note</type>
<price></price>
<yield></yield>
<callable>Yes</callable>
<frequency>Semi-Annual</frequency>
<first_payment>2/17/2005</first_payment>
</bond>
</bonds>

Let's generate this file from Rake.

1. Generate a new Rails application by typing rails code_generator (or whatever you wish to call your helper application)
2. Change RAILS_ROOT/config/database.yml to point to your applications DB

development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000



3. Create a file named something like generator.rb in RAILS_ROOT/lib/tasks
4. Require ERB at the top of this file.
require 'erb'


5. Add a method to send the contents of a table to an ERB template named table.type.erb . Notice the second to last line of the method below. It's where we pass the binding method to ERB. this will make all our variables and methods available to the ERB template we create later, including the dataset variable and the table variable.


def process_erb(type,table)

# Grab our ERB template
template = ERB.new(IO.readlines("lib/tasks/table.#{type}.erb").to_s

# Use Active Record to get our dataset from the DB
dataset = ActiveRecord::Base.connection.execute("select * from #{table.underscore}")

# Create a new file for the ERB output
file_name = "#{file_name}.#{type}"
f = File.new("#{file_name}",'w')

# Write the ERB output to the new file:
f.puts(template.result(binding))
f.close
end


6 . Add a rake task to call our method to create an XML file.
TABLE = ENV['TABLE']

task :create_xml => [:environment] do
process_erb("xml",TABLE)
end


7. All we need is the ERB template named table.xml.erb We write this taking advantage of the dataset and table variables available to us from the ruby binding.

<<%=table.underscore.pluralize%>>
<% dataset.each{|row| %>
<<%=table.underscore.pluralize%>>
<% row.each{ |k,v| %>
<<%=k%>><%=v%></<%=k%>>
<% } %>
</<%=table%>>
<% } %>
</<%= table.underscore.pluralize %>>
8. Our method expects a table name at the command line , so we'll call it with
rake create_xml TABLE=bond

The result is a bonds.xml file with our desired data!

9. Notice how our template name contains our desired file type, xml, then our method takes this as a parameter. How easy will it be now to create a table.java.erb template, and call it? How about a template called table.php.erb ?

10. How about running this generator from jRuby to access an Oracle database?

development:
adapter: jdbc
driver: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@oracle.apptrain.com:1521:xe
username: test





115 comments:

Gunnie said...

I'd replace erb with http://builder.rubyforge.org/ if it would help

Mike said...

Hi , Yes Builder is great just for creating XML, but erb, or (or any template system) gives you the flexibility to create templates for multiple file types. On this project we were also generating .java files. I need to do a follow up post one of these days.

murali karthik said...

Hi friends, This is Murali from Chennai. I am a technology freak. Your technical information is really useful for me. Keep update your blog.
Regards..
Oracle Training in Chennai

anu devid said...

I am an advancement hulk.Oracle Training in Chennai Your specific information is genuinely significant Oracle Training in Chennai for me. Keep overhaul your site.

Regards..

anu devid said...

Hi , Yes Builder Oracle Training in Chennai is magnificent just for making Informatica Training in Chennai XML, yet erb, (or any configuration system) issues you the versatility to make formats for distinctive Besant Technologies Reviews report sorts.

Amirtha rao said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
Regards,
Informatica training in chennai|Informatica training center in Chennai

Melisa said...

Thanks for sharing this useful post; Actually Salesforce crm cloud application provides special cloud computing tools for your client management problems. It’s a fresh technology in IT industries for the business management.
Regards,
Salesforce training in Chennai|Salesforce training institute in Chennai|Salesforce training

Andria BZ said...

Thanks for sharing this niche useful informative post to our knowledge, Actually SAP is ERP software that can be used in many companies for their day to day business activities it has great scope in future.
Regards,
SAP course in chennai|SAP training|SAP Institutes in Chennai|SAP Training Chennai

Paul Miller said...

Cloud is one of the tremendous technology that any company in this world would rely on(Salesforce Certification). Using this technology many tough tasks can be accomplished easily in no time. Your content are also explaining the same(Salesforce crm training in chennai). Thanks for sharing this in here. You are running a great blog, keep up this good work(hadoop training).

Isha Gupta said...


I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
Oracle Training in chennai

Isha Gupta said...


I was looking about the Oracle Training in Chennai for something like this ,Thank you for posting the great content..I found it quiet interesting, hopefully you will keep posting such blogs…
Oracle Training in chennai

Isha Gupta said...

It's very good blog which seems very helpful information. Thanks for sharing this post. Keep further posting...!!
Informatica Training in chennai

Isha Gupta said...

Your post is reasonable giving Hadoop Training in Chennai supported it and had an extraordinary time understanding it.
Continue sharing such essential posts. Hadoop Training in Chennai

Isha Gupta said...

Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.I get a lot of great information from this blog. Thank you for your sharing this informative blog.
Pega Training in Chennai

Isha Gupta said...


I have read your blog and i got a very useful and knowledgeable information from your blog.You have done a great job.
SAS Training in Chennai

Isha Gupta said...


Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
QTP Training in Chennai

Isha Gupta said...


This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic
Greens Technologies In Chennai

Isha Gupta said...


Pretty article! I found some useful information in your blog, it was awesome to read,
thanks for sharing this great content to my vision, keep sharing..
Greens Technologies In Chennai

Revathi S said...


Thanks for sharing amazing information about pega Gain the knowledge and hands-on experience you need to successfully design, build and deploy applications with pega. Pega Training in Chennai

Revathi S said...

Who wants to learn Informatica with real-time corporate professionals. We are providing practical oriented best Informatica training institute in Chennai. Informatica Training in chennai

Revathi S said...

QTP is a software Testing Tool which helps in Functional and Regression testing of an application. If you are interested in QTP training, our real time working. QTP Training in Chennai

Revathi S said...

QTP is a software Testing Tool which helps in Functional and Regression testing of an application. If you are interested in QTP training, our real time working. QTP Training in Chennai

Revathi S said...

Looking for real-time training institue.Get details now may if share this link visit Oracle Training in chennai

Revathi S said...

Hey, nice site you have here!We provide world-class Oracle certification and placement training course as i wondered Keep up the excellent work experience!Please visit Greens Technologies located at Chennai Adyar Oracle Training in chennai

Revathi S said...

Awesome blog if our training additional way as an SQL and PL/SQL trained as individual, you will be able to understand other applications more quickly and continue to build your skill set which will assist you in getting hi-tech industry jobs as possible in future courese of action..visit this blog Green Technologies In Chennai

Revathi S said...

Nice site....Please refer this site also Our vision succes!Training are focused on perfect improvement of technical skills for Freshers and working professional. Our Training classes are sure to help the trainee with COMPLETE PRACTICAL TRAINING and Realtime methodologies. Green Technologies In Chennai

Revathi S said...

if share valuable information about hadoop training courses, certification, online resources, and private training for Developers, Administrators, and Data Analysts may visit Hadoop Training in Chennai

Revathi S said...

let's Jump Start Your Career & Get Ahead. Choose sas training method that works for you. This course is designed for professionals looking to move to a role as a business analyst, and students looking to pursue business analytics as a career. SAS Training in Chennai

harithasri said...

Greens Technology offer a wide range of training from ASP.NET , SharePoint, Cognos, OBIEE, Websphere, Oracle, DataStage, Datawarehousing, Tibco, SAS, Sap- all Modules, Database Administration, Java and Core Java, C#, VB.NET, SQL Server and Informatica, Bigdata, Unix Shell, Perl scripting, SalesForce , RedHat Linux and Many more.

harithasri said...

Greens Technologies Training In Chennai Excellent information with unique content and it is very useful to know about the information based on blogs.

harithasri said...

Thanks for sharing this nice useful informative post to our knowledge, Actually SAS used in many companies for their day to day business activities it has great scope in future.

harithasri said...

Our HP Quick Test Professional course includes basic to advanced level and our QTP course is designed to get the placement in good MNC companies in chennai as quickly as once you complete the QTP certification training course.

harithasri said...

A Best Pega Training course that is exclusively designed with Basics through Advanced Pega Concepts.With our Pega Training in Chennai you’ll learn concepts in expert level with practical manner.We help the trainees with guidance for Pega System Architect Certification and also provide guidance to get placed in Pega jobs in the industry.

harithasri said...

Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
Informatica Training In Chennai

harithasri said...

There are lots of information about latest technology and how to get trained in them, like Hadoop Training Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies(Hadoop Training in Chennai). By the way you are running a great blog. Thanks for sharing this

harithasri said...

Oracle Training in Chennai is one of the best oracle training institute in Chennai which offers complete Oracle training in Chennai by well experienced Oracle Consultants having more than 12+ years of IT experience.

harithasri said...

It is really very helpful for us and I have gathered some important information from this blog.
Oracle Training In Chennai

Ravindra Reddy said...

Very useful info about online trainings,thanks for sharing these articles.

SCCM 2012 Online Training

Selenium Online Training

Solaris Online Training

Raksha said...

Found your post to be very useful and informative. Appreciate the great work.
Best HTML5 Training in Chennai | Best HTML5 Training in Chennai

Saranya D said...

1
hai you have to learned to lot of information about c# .net Gain the knowledge and hands-on experience you need to successfully design, build and deploy applications with c#.net.
C-Net-training-in-chennai

Saranya D said...



hai If you are interested in asp.net training, our real time working.
asp.net Training in Chennai.
Asp-Net-training-in-chennai.html

Saranya D said...


Amazing blog if our training additional way as an silverlight training trained as individual, you will be able to understand other applications more quickly and continue to build your skill set which will assist you in getting hi-tech industry jobs as possible in future courese of action..visit this blog
silverlight-training.html
greenstechnologies.in:

Saranya D said...


Amazing blog if our training additional way as an silverlight training trained as individual, you will be able to understand other applications more quickly and continue to build your skill set which will assist you in getting hi-tech industry jobs as possible in future courese of action..visit this blog
silverlight-training.html
greenstechnologies.in:

Saranya D said...



awesome Job oriented sharepoint training in Chennai is offered by our institue is mainly focused on real time and industry oriented. We provide training from beginner’s level to advanced level techniques thought by our experts.
if you have more details visit this blog.
SharePoint-training-in-chennai.html

Saranya D said...


if share valuable information about cloud computing training courses, certification, online resources, and private training for Developers, Administrators, and Data Analysts may visit
Cloud-Computing-course-content.html

sss lokesh said...

amazing app this is the trend....
Tableau Training || Tableau Online Training

Santhiya said...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
QTP Training in Chennai

Raksha said...

Hello Admin, thank you for the article. It has helped me during my Java training in Chennai. Fita academy is a Java training institutes in Chennai that provides training for interested students. So feel free to contact us to join our Java J2EE training institutes in Chennai.

Santhiya said...


In database computing, Oracle Real Application Clusters (RAC) — an option for the Oracle Database software produced by Oracle Corporation and introduced in 2001 with Oracle9i — provides software for clustering and high availability in Oracle database environments. Oracle Corporation includes RAC with the Standard Edition, provided the nodes are clustered using Oracle Clusterware.
Oracle RAC allows multiple computers to run Oracle RDBMS software simultaneously while accessing a single database, thus providing clustering.

In a non-RAC Oracle database, a single instance accesses a single database. The database consists of a collection of data files, control files, and redo logs located on disk. The instance comprises the collection of Oracle-related memory and operating system processes that run on a computer system.

Oracle RAC Training in Chennai

Akula Rajitha said...

TNPSC 813 Village Administrative Officer Recruitment 2015

Ideal and clear cut explanation...... Very Impressive and useful information, Thanks to author for sharing.............

Rashmi D'souza said...

Thanks for sharing this informative blog..
Core Java Training In Chennai

Akasha said...

This information is impressive..
informatica Training in Chennai

Akula Rahul said...

Naval Dockyard Visakhapatnam Tradesman Skilled Recruitment 2016

Thank you sir, I really like this post...........

jhansi joe said...

I have read your blog, it was good to read & I am getting some useful info's through your blog keep sharing... Informatica is an ETL tools helps to transform your old business leads into new vision. Learn informatica training in Chennai from corporate professionals with very good experience in informatica tool.
Regards,
Informatica training in chennai|Best Informatica Training In Chennai|sas training in Chennai

for IT the said...

Great Article
Online Java Training | Java EE course

Java Course in Chennai | Java Training in Chennai | Java Training Institutes in Chennai | J2EE Training in Chennai | java j2ee training institutes in chennai

Java 360 | IT Technical Articles |Java Training Institutes

ioscare team said...

Such a informative post.Thanks for sharing your knowledge with us.keep it up for updating post..
http://sonymobileservicecenterinchennai.in/AboutUs.html

Melisa said...

Awesome Post! I like writing style, how you describing the topics throughout the post. I hope many web reader will keep reading your post at the end, Thanks for sharing your view.
Regards,
Linux Certification|Linux Course in Chennai|Linux Administration Training in Chennai

Savitha said...

great article!!!!!This is very importent information for us.I like all content and information.I have read it.You know more about this please visit again.
Informatica Training In Chennai
Hadoop Training In Chennai
Oracle Training In Chennai
Pega Training In Chennai

jhansi joe said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
Regards,
Informatica training chennai|Informatica training institutes in Chennai|Informatica training center in Chennai

geethu said...

Great content. I really enjoyed while reading this content with useful information, keep sharing.
Hadoop Training in Chennai | Hadoop Training Chennai | FITA Velachery | FITA Academy Chennai.

Diya Patel said...

Best SQL Query Tuning Training Center In ChennaiIt’s too informative blog and I am getting conglomerations of info’s about Oracle interview questions and answer .Thanks for sharing, I would like to see your updates regularly so keep blogging.

Harini said...

This post is really nice and informative. The explanation given is really comprehensive and informative..
SAS Training In Chennai

ind jobs jobs guru said...

An awesome post..
Latest indian Jobs

Aditya Sharma said...

Happy Valentines Day 2016 Quotes SMS Cards Images

Happy Valentines Day 2016 Quotes

Happy Valentines Day 2016 SMS

Valentines Day 2016 Cards

Valentines Day 2016 Images

Valentine Day 2016 Gift Ideas

Valentine Day 2016 Wishes

Valentines Day 2016 Quotes

Happy Valentine Day 2016 Messages

Govt Jobs said...

thanks for the Nice Information in the post


Egovtjobs

ind jobs jobs guru said...

An awesome post

Latest indian Jobs

Marissa Ryan said...

Nice post. I learned something knowledgeable.


IELTS classes in Kuwait

Nitish Lakhera said...

Result

John Vessy said...

Ap 10th Results 2016

I would like to tell you thanks for the great details for the all jobs................

Geetha said...

very informative blog. Helps to gain knowledge about new concepts and techniques. Thanks for posting information in this blog
Hadoop Training in Chennai

karthika revathi said...

thanks for sharing this nice information.wonderful article to know more.your way of explanation is good.



HADOOP Training in Chennai

Geetha said...

This blog is impressive and informative.It clearly explains about the concept and its techniques.Thanks for sharing this information.Please update this type of
information
sas Training in Chennai



Arjun Rishi said...

Wonderful post. I like it. Thanks for sharing.


digital marketing training in chennai

prathap kumar said...

I have read your blog its very attractive and impressive. I like it your blog.

Dot Net Training in Chennai | Online Dot Net Training

Online Dot Net Training | Online LINQ Training

prathap kumar said...

I have read your blog its very attractive and impressive. I like it your blog.

Dot Net Training in Chennai | Online Dot Net Training

Online Dot Net Training | Online LINQ Training

prathap kumar said...

Java Training in Chennai | Core Java Training in Chennai

Online Java Training | Java EE Training Institute in Chennai

prathap kumar said...

Angularjs Training in Chennai | Backbone.JS Training in Chennai | Bootstrap Training in Chennai | Node.js Training in Chennai | Typescript Training in Chennai

prathap kumar said...

Java Articles | IT Technical Articles | Dot Net Framework Articles |
JavaScript Articles | Java Training Institutes | Single Page Application Development

Chinni Bocha said...

thanku for giving this information..
SEO training in hyderabad by experts in digital markeing And by prosessional experts in seo.All the training by placement and also guide by the professionals.SEO training in hyderabad

Rakesh S said...

valuable information..
Informatica online training in hyderabad

advitha said...

I really admire you writing style and the article you had written Which is very interesting keep posting

IBPS PO 2016 Notification Exam Dates

SAP Hybris Online Training said...

W3 D Technologies provide comprehensive SAP HYBRIS Online Training through industry SAP experts, aiming with Right knowledge about B2B Multi channel eCommerce SAP Hybris that best suits your needs.

SAP HYBRIS Online Training

Rakesh S said...

code generations nice posts..


Hadoop training in hyderabad.All the basic and get the full knowledge of hadoop.
hadoop training in hyderabad

Arjun Rishi said...

Excellent post ! keep sharing such a useful post.

seo training course in Chennai

Balarishi said...

Great post. Glad to find your blog. Thanks for sharing.


Android Course in Chennai

Rakesh S said...

code generation for using rails ..Gret!!!
Hadoop training in hyderabad.All the basic and get the full knowledge of hadoop.
hadoop training in hyderabad


Anu Sri said...

Wonderful post. Keep sharing such a useful post.

magento training in chennai

Tony Starck said...
This comment has been removed by the author.
Raja B said...

Big data and data warehousing related information is always updated to me at hadoop online training in hyderabad. Nice insight on the topic refer the details at
hadoop online training

Balarishi said...

You shared useful post. happy to visit your blog. Keep sharing.

AngularJs Training

Happy Diwali said...
This comment has been removed by the author.
Happy Diwali said...

Here we have gathered couple of HAPPY DIWALI IMAGES 2016 Wallpapers SMS in English Hindi Marathi Bhojpuri Punjabi.So that you can duplicate these Happy Diwali Messages and forward to your Loved Ones.Best Happy New year status

Anu Sri said...

Excellent post! keep sharing such a useful sharing.


web design course in chennai

Logavani G said...

hi to all.really you have post an informative blog.it will be really helpful to many peoples.thank you for sharing this blog.
Salesforce Training

Siddarth said...

I really admire you writing style and the article you had written Which is very interesting keep posting

Hyderabad Metro Rail Recruitment

Siddarth said...

Hi, thanks for the information provided in the article.

UP Jal Nigam JE AE Recruitment

mythily mythu said...

nice postining...
base-sas training in chennai

mythily mythu said...

good.. android training in chennai

Nandhini said...

Thanks for sharing this informative content which provided me the required information about the latest technology.
Salesforce training in Chennai | Salesforce course in Chennai

sunilkumarkuppam said...

Thanks for sharing the information about the Salesforce training.We are offering the Salesforce training in Chennai at Fita.
salesforce training in chennai
Salesforce Certification

Ccna Training said...

great links thanks for sharing. CCNA Training in Pune | hadoop training in

pune
| java training in pune | digital marketing training in pune

subbu said...

Good website! I really love how it is simple on my eyes and the data are well written.

sap abap online training

sap basis online
training


sap bo admin online training

sap controlling online training

Manasa Garugu said...

Sarkari Recruitment is one of the biggest Indian Job Site so here you will getHPPSC Jobs 2017 so

KARTHIK said...

telangana ssc supplementary results 2017

ts ssc supply results 2017

ts ssc hall ticket 2017 date

This site is very good I like this website

Manasa Garugu said...

Good information. Keep sharing this kind of useful info. AP 10th Class Result 2017

Reshma said...

Great stuff. Glad to see such a useful infoKerala SSLC Result 2017 So

ramya said...

Good information. Keep sharing this kind of useful info. Maha Board Inter 1st Year Result

Reshma said...

Thank you for the useful information. You might be interested in MP Board 12th 1st year Result So

Reshma said...

Thank you for the useful information. Check Mizoram Board 12th 1st year Result So

Unknown said...

Jobs Chat is one of the biggest Indian Job Site so here you will getGovt jobs in andhrapradeshso

kingrani said...

AP Exam Results is Now releasing Manabadi ap 10th class results 2017 and also Releasing
manabadi Ap eamcet results 2017 , SO Take Time and Check Out Apexamresults website For fast servers and More





kingrani said...

Jobs Chat is one of the biggest Indian Job Site so here you will getLatest Govt jobs in 2017-2018so

digi member said...


aai recruitment

ecil recruitment

ts-tet recruitment

Kavya said...

Great Website. Good to see this. WBAIC Syllabus

Tom McDonald said...

Thank you for a great article and a nice place! I am now a permanent guest. Read more...

Popular Articles