Since I have a lot of Java works to do right now, I stop learning Ruby on Rails. Also, it is quite hard to find a job that requires Ruby on Rails skill in Thailand, it is worth not much for me to learn it at the present. I decided to switch to Scala instead because it is quite close to Java and some companies in Thailand using it, also support functional programming and DCI (Data, Context and Interaction) which I would like to practice the most.
Further posts will be about Scala and DCI, I will start by walkthrough the Getting Started with Scala Tutorial and then demonstrate how I apply DCI to an application written by using Scala.
I am Thai Software Craftsman
วันอาทิตย์ที่ 30 ตุลาคม พ.ศ. 2554
วันอาทิตย์ที่ 23 ตุลาคม พ.ศ. 2554
Ruby on Rails - Rails Routing
The topic I'm writing today is about how we map URLs to corresponding resources by using Rails Routing feature. The Rails Router is a component that manage this. It recognizes URLs and dispatches them to a controller's action.
Rails will map the HTTP verbs and URLs to the QuotesController's actions as follows:
Also, the resource routing supports the namespace and nested resources, you can find more information at this link, http://guides.rubyonrails.org/routing.html.
In this post, I would like to give the basic idea of the resource routing. When I use the advance features, I will post more about them later.
Have a nice week end :D.
For example, when you enter http://localhost:3000/quotes/1 to the address bar of the web browser and in the config/routes.rb file contain the following line:
match "/quotes/:id" => "quotes#show"
The Router will dispatch /quotes/1 to the quote controller's show action with { :id => 1 } in params. Also, we can generate a link to a particular quote by using the link_to helper; the information in the routes.rb will be used in generating the link as the example shown below.
<%= link_to "Link to this page", quote_path(@quote)%>
If we put the above code in the show.html.erb file for the quote, the result is as the following screenshot:
In addition, the RoR also provide the resource routing, it allows us to declare all of the common routes for a given resourceful controller. Browsers request pages from Rails by making HTTP requests with a specific HTTP method; GET, POST, PUT and DELETE. Each method is for performing an operation on the requested resource. A resource route will map a specified HTTP method to corresponding action in a single controller.
Let's assume that we have the resources declaration for the Quote controller
resources: quotes
and a browser make the HTTP request
DELETE /quotes/2
When Rails receives the HTTP request, it will map the request to the destroy method of the QuotesController as shown below.
def destroy
@quote = Quote.find(params[:id])
@quote.destroy
respond_to do |format|
format.html { redirect_to quotes_url }
format.json { head :ok }
end
end
The HTTP methods or verbs along with requested URLs will be mapped to corresponding actions of a controller. Referring to the resources declaration above all the HTTP verbs and corresponding controller's actions as shown below.
Rails provides a number of the helpers for generating URLs that are mapped to the controller's actions such as:
<%= link_to "Link to this page", quote_path(@quote)%>
If we put the above code in the show.html.erb file for the quote, the result is as the following screenshot:
In addition, the RoR also provide the resource routing, it allows us to declare all of the common routes for a given resourceful controller. Browsers request pages from Rails by making HTTP requests with a specific HTTP method; GET, POST, PUT and DELETE. Each method is for performing an operation on the requested resource. A resource route will map a specified HTTP method to corresponding action in a single controller.
Let's assume that we have the resources declaration for the Quote controller
resources: quotes
and a browser make the HTTP request
DELETE /quotes/2
When Rails receives the HTTP request, it will map the request to the destroy method of the QuotesController as shown below.
def destroy
@quote = Quote.find(params[:id])
@quote.destroy
respond_to do |format|
format.html { redirect_to quotes_url }
format.json { head :ok }
end
end
The HTTP methods or verbs along with requested URLs will be mapped to corresponding actions of a controller. Referring to the resources declaration above all the HTTP verbs and corresponding controller's actions as shown below.
HTTP Verb
|
Path
|
Action
|
Description
|
GET
|
/quotes
|
index
|
Show a list of all quotes
|
GET
|
/quotes/1
|
show
|
Show the detail of the quote (ID 1)
|
GET
|
/quotes/new
|
new
|
Show the form for creating a new quote
|
POST
|
/quotes
|
create
|
Create a new quote
|
GET
|
/quotes/1/edit
|
edit
|
Show the form for modifying the quote (ID 1)
|
PUT
|
/quotes/1
|
update
|
Update the quote (ID 1)
|
DELETE
|
/quotes/1
|
destroy
|
Delete the quote (ID 1)
|
Rails provides a number of the helpers for generating URLs that are mapped to the controller's actions such as:
- quotes_path returns /quotes
- new_quotes_path returns /quotes/new
- quote_path returns /quotes/:id, where :id is a quote ID
The resource routing for a singular resource is supported by using the match, as I shown earlier, or give the resources declaration a singular resource, such as:
resources :quote
Rails will map the HTTP verbs and URLs to the QuotesController's actions as follows:
HTTP Verb
|
Path
|
Action
|
Description
|
GET
|
/quote
|
show
|
Show the detail of the quote
|
GET
|
/quote/new
|
new
|
Show the form for creating a new quote
|
POST
|
/quote
|
create
|
Create a new quote
|
GET
|
/quote/edit
|
edit
|
Show the form for modifying the quote
|
PUT
|
/quote
|
update
|
Update the quote
|
DELETE
|
/quote
|
destroy
|
Delete the quote
|
Also, the resource routing supports the namespace and nested resources, you can find more information at this link, http://guides.rubyonrails.org/routing.html.
In this post, I would like to give the basic idea of the resource routing. When I use the advance features, I will post more about them later.
Have a nice week end :D.
วันอาทิตย์ที่ 16 ตุลาคม พ.ศ. 2554
Ruby on Rails - Validating Values Passed to Models
Today I will continue from the RoR article I wrote about the Relationship Between Model. After the model relationship is defined, it is important to check if values passed to the model are valid. In the RoR, we can validate the values by using the validates method provided by the RoR as the example shown below.
The validates method check whether a given field, :iname and :bid for example, has a value or not. If not the error will be raised to the application and we can check the error in the errors field or the model.
Beside the :presence validation helper, the RoR also provide the other helpers for checking values sent to the model. Please refer to this link for the helpers available in the RoR.
http://guides.rubyonrails.org/active_record_validations_callbacks.html
This is quite handy feature, reducing the times required to write the code for validating the values. In past, I developed the web applications by using just PHP, no web framework. It is quite painful and take sometime to write these things and fix bugs made by my mistake. Beside it helps to reduce the time and bugs in developing these validation methods, one benefit is maintainability of the code base. Since the code we need to write for these things are provided by the framework, we have not to maintain them also test when there are changes in those validation methods.
Referring to the project I'm building, Real-Time Quotes, all the fields should have a value and its type should follow this specification.
The iname field is a name of an instrument in a quote.
The bid field is a bid price of an instrument in a quote.
The ask field is an ask price of an instrument in a quote.
The trdprc field is a trade price of an instrument in a quote.
Therefore, three validations need to be added to the Quote model class to check whether a value is presence and a floating point number if it is a type of price field as the example shown below.
From the code above, you will see that the price type fields can be validated if they are a floating by using the :numericality helper. Try to put a non-numeric character to the bid, ask or price will produce the error as shown below.
The error dialog displayed is the default one generated by the RoR. We can change the style of the dialog by modifying the style sheet for the error in the /assets/scaffolds.css.css file. For example, if you like to change the background color of the field when an error occurs, modifying the .field_with_errors style as shown below.
.field_with_errors {
padding: 2px;
background-color: orange;
display: table; }
The error will be displayed with the background color in orange instead as illustrated below.
You can also add other attributes, border-color or font-size for example, to the style sheet to make a look-and-feel you prefer. That's all I have learned today. Hope you enjoy my post and have a nice day :)
class Quote < ActiveRecord::Base
validates :iname, :presence => true
validates :bid, :presence => true
has_many :quote_news
end
The validates method check whether a given field, :iname and :bid for example, has a value or not. If not the error will be raised to the application and we can check the error in the errors field or the model.
Beside the :presence validation helper, the RoR also provide the other helpers for checking values sent to the model. Please refer to this link for the helpers available in the RoR.
http://guides.rubyonrails.org/active_record_validations_callbacks.html
This is quite handy feature, reducing the times required to write the code for validating the values. In past, I developed the web applications by using just PHP, no web framework. It is quite painful and take sometime to write these things and fix bugs made by my mistake. Beside it helps to reduce the time and bugs in developing these validation methods, one benefit is maintainability of the code base. Since the code we need to write for these things are provided by the framework, we have not to maintain them also test when there are changes in those validation methods.
Referring to the project I'm building, Real-Time Quotes, all the fields should have a value and its type should follow this specification.
The iname field is a name of an instrument in a quote.
The bid field is a bid price of an instrument in a quote.
The ask field is an ask price of an instrument in a quote.
The trdprc field is a trade price of an instrument in a quote.
Therefore, three validations need to be added to the Quote model class to check whether a value is presence and a floating point number if it is a type of price field as the example shown below.
class Quote < ActiveRecord::Base
validates :iname, :presence => true
validates :bid, :presence => true, :numericality => true
validates :ask, :presence => true, :numericality => true
validates :trdprc, :presence => true, :numericality => true
has_many :quote_news
end
From the code above, you will see that the price type fields can be validated if they are a floating by using the :numericality helper. Try to put a non-numeric character to the bid, ask or price will produce the error as shown below.
The error dialog displayed is the default one generated by the RoR. We can change the style of the dialog by modifying the style sheet for the error in the /assets/scaffolds.css.css file. For example, if you like to change the background color of the field when an error occurs, modifying the .field_with_errors style as shown below.
.field_with_errors {
padding: 2px;
background-color: orange;
display: table; }
The error will be displayed with the background color in orange instead as illustrated below.
You can also add other attributes, border-color or font-size for example, to the style sheet to make a look-and-feel you prefer. That's all I have learned today. Hope you enjoy my post and have a nice day :)
วันพฤหัสบดีที่ 13 ตุลาคม พ.ศ. 2554
Vi and Emac
Vi editor is the first edit I used in Unix when I was in the university. Even though it does not have an impressive user interface and not easy to use at the first time like the others but it is powerful and fast in searching text in a editing file. If you remember main keys of Vi, you can edit a file without using a mouse. It can open very hug file , more than 100 MB or may be several GB that some editors cannot do. The other thing I like are that the command mode that enable you to move lines around file or replace text with a few efforts.
Present, I still use Vi for sometimes and learning to use another editor called Emac. I heard about this editor since I was in the university as well. My prof. told me that it is an elegant editor that most Unix developers use. It has many features that enable coding and editing more easy and productive. Not surprise, after learning it for a few days now I understand what my prof. means. With combination of control and character keys, it provide a lot of ways of editing experience; file and directory searching, multiple windows for editing, shell command running and buffer handling. Also, integrated with famous version control systems and diff tools. I just begin using and learning all basics and tips to get the most out of it.
Present, I still use Vi for sometimes and learning to use another editor called Emac. I heard about this editor since I was in the university as well. My prof. told me that it is an elegant editor that most Unix developers use. It has many features that enable coding and editing more easy and productive. Not surprise, after learning it for a few days now I understand what my prof. means. With combination of control and character keys, it provide a lot of ways of editing experience; file and directory searching, multiple windows for editing, shell command running and buffer handling. Also, integrated with famous version control systems and diff tools. I just begin using and learning all basics and tips to get the most out of it.
วันอาทิตย์ที่ 9 ตุลาคม พ.ศ. 2554
Reading Book - Program Development in Java: Abstraction, Specification, and Object-Oriented Design
Beside writing the blog, one thing I love to do is reading new programming or software design books. Currently, I'm working on a quite large and very complex Java based software. Only the programming knowledge I have is not enough to deal with this kind of software. Learning different design and programming approaches is one way could help me to tackle problems in software developments.
The book I'm currently reading is Program Development in Java: Abstraction, Specification, and Object-Oriented Design, written by Barbara Liskov and John Guttag.
Preview
Barbara Liskov is quite well known in the software industry. She is who define the Liskov Subsitution Principle, one of the SOID principles. I'm reading the Chapter 1. Introduction, it is about the Decomposition and Abstraction which I think ones of the most important topics and techniques used in software developments.
She explains that a large program should be decomposed into a number of small independent programs, called modules. Developing the large program involves many people and require a number of communications between them to ensure they have the same understanding in each part of the program with which their program need to interact, and this consumes too much time.
Decomposing the program into pieces which the individual can work on it independently will help to reduce the communications and misunderstandings.
This is what I got from the book right now. Will share more about it later as I go on through the book. Have a nice day :)
The book I'm currently reading is Program Development in Java: Abstraction, Specification, and Object-Oriented Design, written by Barbara Liskov and John Guttag.
Preview
Barbara Liskov is quite well known in the software industry. She is who define the Liskov Subsitution Principle, one of the SOID principles. I'm reading the Chapter 1. Introduction, it is about the Decomposition and Abstraction which I think ones of the most important topics and techniques used in software developments.
She explains that a large program should be decomposed into a number of small independent programs, called modules. Developing the large program involves many people and require a number of communications between them to ensure they have the same understanding in each part of the program with which their program need to interact, and this consumes too much time.
Decomposing the program into pieces which the individual can work on it independently will help to reduce the communications and misunderstandings.
This is what I got from the book right now. Will share more about it later as I go on through the book. Have a nice day :)
วันเสาร์ที่ 8 ตุลาคม พ.ศ. 2554
Ruby on Rails - The Project I Would Like To Do
I started writing the posts about what I learned from the Ruby on Rails tutorial. However, I have not mentioned about what kind of project I would like to do yet. Therefore, it would be good to let you know my project before continuing to write further posts.
Since I am working at the department that its products are used in the financial industry, the project I aim to develop is also related to my field; the Real-Time Quotes web application.
The Real-Time Quotes web application is a Ruby on Rails based application will be deployed as example in Heroku platform which has the following features.
In my view, the most effective way to learn new programming languages or frameworks is to do some projects that are close to the real ones as much as possible; this will make you to think about it as you are doing the project for a real client and try to configure out what are important to learn and practise the most to get the product out to the client's hands. It could help to boost your performance in learning new things a lot.
Since I am working at the department that its products are used in the financial industry, the project I aim to develop is also related to my field; the Real-Time Quotes web application.
The Real-Time Quotes web application is a Ruby on Rails based application will be deployed as example in Heroku platform which has the following features.
- Display real-time quotes simulated from the Quote Feed web application.
- Display real-time news related to a particular quote simulated from the Quote News web application.
- Display historical quotes simulated from the Historical Quote web application.
- All information provided from the web applications will be in JSON format.
- Front-End User Interfaces are an Ajax + HTML5 and JavaScript based that pull data from the web applications.
In my view, the most effective way to learn new programming languages or frameworks is to do some projects that are close to the real ones as much as possible; this will make you to think about it as you are doing the project for a real client and try to configure out what are important to learn and practise the most to get the product out to the client's hands. It could help to boost your performance in learning new things a lot.
ป้ายกำกับ:
Ajax,
Historical Quotes,
HTML5,
JavaScript,
JSON,
News,
Quotes,
Real-Time
วันพุธที่ 5 ตุลาคม พ.ศ. 2554
Ruby on Rails - Relationship Between Models
I would like to start with the basic knowledge I gained from the RoR tutorial at http://guides.rubyonrails.org/getting_started.html, how to associate a particular model to one another. In the RoR, simply just put the belong_to statement, followed by a name of the model you want to make the association, into the target model as the example code shown below.
The statement defines that the QuoteNews class belong to the Quote class. Beside add the belong_to statement to the QuoteNews class, we have to define the relationship in the CreateQuoteNews class as well as the following code.
The t.references statement define a foreign key column for the association between the two models. The add_index statement define an index for the association column. When we run the rake db:migrate command, the association between the models will be create in the database as we define in the CreateQuoteNews class.
Also, the has_many statement need to be added to the Quote class therefore; we can retrieve associated QuoteNews via the Quote class as shown below.
Now we associate the two models togather, next we will create the controller for the QuoteNews model therefore; we can add a new quote news data to the database and then show it in the same page as the quote detail. I will share how we can do this later in the next post.
class QuoteNews < ActiveRecord::Base
belongs_to :quote
end
The statement defines that the QuoteNews class belong to the Quote class. Beside add the belong_to statement to the QuoteNews class, we have to define the relationship in the CreateQuoteNews class as well as the following code.
class CreateQuoteNews < ActiveRecord::Migration
def change
create_table :quote_news do |t|
t.string :title
t.text :content
t.references :quote
t.timestamps
end
add_index :quote_news, :quote_id
end
end
def change
create_table :quote_news do |t|
t.string :title
t.text :content
t.references :quote
t.timestamps
end
add_index :quote_news, :quote_id
end
end
The t.references statement define a foreign key column for the association between the two models. The add_index statement define an index for the association column. When we run the rake db:migrate command, the association between the models will be create in the database as we define in the CreateQuoteNews class.
Also, the has_many statement need to be added to the Quote class therefore; we can retrieve associated QuoteNews via the Quote class as shown below.
class Quote < ActiveRecord::Base
validates :iname, :presence => true
validates :bid, :presence => true
has_many :quote_news
end
validates :iname, :presence => true
validates :bid, :presence => true
has_many :quote_news
end
Now we associate the two models togather, next we will create the controller for the QuoteNews model therefore; we can add a new quote news data to the database and then show it in the same page as the quote detail. I will share how we can do this later in the next post.
สมัครสมาชิก:
บทความ (Atom)