HowTo: Changing the column name in a model for validation
Sample code taken from here.
class User > ActiveRecord::Base
HUMANIZED_ATTRIBUTES = {
:email => “E-mail address”
}def self.human_attribute_name(attr)
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
endend
String#present?
>> “brain”.present?
=> true
>> “”.present?
=> false
use something.present?
instead of !something.blank?
HowTo: Add Ajax Indicators
Copy the following code to public/javascripts/application.js
Ajax.Responders.register({
onCreate: function() {
if (Ajax.activeRequestCount > 0)
Element.show('indicator');
},onComplete: function() {
if (Ajax.activeRequestCount == 0)
Element.hide('indicator');
}
});
Add a div element to your view with an id of ‘indicator’. Remember to keep this div from displaying by setting the display attribute to none.
#indicator{style => 'display:none'}
= image_tag ('/images/my_loading_indicator.gif')
Here is a good site to create your own indicator image.
HowTo: Use older gems
Now that Rails 2.1.1 is out, when you install using the gem, you get Rails 2.1.1. If you want to install an older version, like Rails 2.1.0, you need to specify the version:
sudo gem install rails –version 2.1.0
You’ll do this if you have some dependency on the older rails version. To make sure your app will run when you transfer to a different machine, freeze rails into the vendor directory:
rake rails:freeze:edge TAG=rel_2-1-0
Make sure that your environment.rb specifies the corresponding version.
Finally, you may want to create a new project using an older version of rails. You can do so by:
rails _2.1.0_ project_name
And apparently, you can use that trick for other gem-installed commands, like capistrano.
HowTo: Date operations
I’m just going to copy and paste the code from this site.
Basically, time and date manipulations are easy as long as the operations involved are additions and subtractions. Quoted from the link above:
Not every arithmetic operation makes sense for dates: you could “multiply two dates” by multiplying the underlying numbers, but that would have no meaning in terms of real time, so Ruby doesn’t define those operators.
Remember:
- Time has a unit of 1 secondrequire ‘date’
y2k = Time.gm(2000, 1, 1) # => Sat Jan 01 00:00:00 UTC 2000
y2k + 1 # => Sat Jan 01 00:00:01 UTC 2000
y2k – 1 # => Fri Dec 31 23:59:59 UTC 1999
y2k + (60 * 60 * 24 * 365) # => Sun Dec 31 00:00:00 UTC 2000y2k_dt = DateTime.new(2000, 1, 1)
(y2k_dt + 1).to_s # => “2000-01-02T00:00:00Z”
(y2k_dt – 1).to_s # => “1999-12-31T00:00:00Z”
(y2k_dt + 0.5).to_s # => “2000-01-01T12:00:00Z”
(y2k_dt + 365).to_s # => “2000-12-31T00:00:00Z” - While DateTime and Date have a unit of 1 dayday_one = Time.gm(1999, 12, 31)
day_two = Time.gm(2000, 1, 1)
day_two – day_one # => 86400.0
day_one – day_two # => -86400.0day_one = DateTime.new(1999, 12, 31)
day_two = DateTime.new(2000, 1, 1)
day_two – day_one # => Rational(1, 1)
day_one – day_two # => Rational(-1, 1)
Printing dates on our views is done by using the method strftime.
d = Date.today # 2008-08-12
d.strftime(‘%b %d, %Y’) # will print August 12, 2008
The following are the format codes. For reference, refer to this site.
| Format | Meaning |
| %a | The abbreviated weekday name (“Sun’’) |
| %A | The full weekday name (“Sunday’’) |
| %b | The abbreviated month name (“Jan’’) |
| %B | The full month name (“January’’) |
| %c | The preferred local date and time representation |
| %d | Day of the month (01..31) |
| %H | Hour of the day, 24-hour clock (00..23) |
| %I | Hour of the day, 12-hour clock (01..12) |
| %j | Day of the year (001..366) |
| %m | Month of the year (01..12) |
| %M | Minute of the hour (00..59) |
| %p | Meridian indicator (“AM’’ or “PM’’) |
| %S | Second of the minute (00..60) |
| %U | Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) |
| %W | Week number of the current year, starting with the first Monday as the first day of the first week (00..53) |
| %w | Day of the week (Sunday is 0, 0..6) |
| %x | Preferred representation for the date alone, no time |
| %X | Preferred representation for the time alone, no date |
| %y | Year without a century (00..99) |
| %Y | Year with century |
| %Z | Time zone name |
| %% | Literal “%’’ character |
HowTo: Add email support
Download the gem from this site and install using
gem install actionmailer-2.1.0.gem
After installing, configure the mailer. In config/environment.rb, add the following lines after the Initializer block,
ActionMailer::Base.delivery_method = :smtpActionMailer::Base.smtp_settings = {
:address => ‘>address<’
:port => ‘, # default: 25
:domain => “”
:user_name => ”,
:password => ”,
:authentication => :login # :plain, :login or :cram_md5
}
Also, change the config.action_mailer.raise_delivery_errors option in config/environments/development.rb to true.
Create a mailer for the project.
ruby script/generate mailer Emailer
Let’s start by adding the following lines to the model.
def signed_up(recipient)
recipients recipient
subject "[Signed up] Welcome #{recipient}"
from "xxx@abc.de"
body :recipient => recipient
end
This method will be used to send the email.
IMPT: the “from” line should have a valid email address on the server or the mail won’t be delivered.
The body of the email is created by creating a view of the same name. So in views/emailer/signed_up.html.erb, place the body of the email you want to send, for example:
Hello there,Mr. <%= @recipient %>
To send the email, you need to append “deliver_” to the method name. So if we need to send the mail to xxx@abc.de, use the following lines
Emailer.deliver_signed_up("xxx@abc.de")
HowTo: Add mobile support
You can also refer here.
First, install the plugin using the following command
ruby script/plugin install git://github.com/brendanlim/mobile-fu.git
Next, in your controllers/application.rb, add the following line:
has_mobile_fu
You can now create a .mobile file for rails to render in place of the html files. And rails will automatically load these files once rails detects that the request to view your page is coming from a mobile source.
If you want to let the users choose between mobile and html view, you can change the session variable
session[:mobile_view]
to true to set users to use the mobile view, false otherwise.
TESTING using Firefox:
To test mobile browsing capabilities using firefox, install the user agent switcher addon. This addon can be found here. After installation, go to
Tools -> User Agent Switcher -> Options -> Options...
and add the user agent of the phone you want to test. A list of user agents for mobile phones is available here.
HowTo: Parse XML using Hpricot
This requires the hpricot plugin.
This is the xml file to be parsed.
<holiday>
<date>
<year>2008</year>
<month>09</month>
<day>23</day>
<type>private</type>
<description>test</description>
</date>
<date>
<year>2008</year>
<month>09</month>
<day>24</day>
<type>company</type>
<description>test2</description>
</date>
<date>
<year>2008</year>
<month>09</month>
<day>25</day>
<type>national</type>
<description>test3</description>
</date>
</holiday>
I put the method in a helper class.
def is_holiday(the_date)
type = “none”
xml_file = File.read(“#{RAILS_ROOT}/public/holiday.xml”)
doc = Hpricot::XML(xml_file)
(doc/:date).each do |xml_date|
if the_date.strftime(“%Y”) == xml_date.at(“year”).innerHTML &&
the_date.strftime(“%m”) == xml_date.at(“month”).innerHTML &&
the_date.strftime(“%e”) == xml_date.at(“day”).innerHTML
then
return type = xml_date.at(“type”).innerHTML
end
end
return type #none
end
Using the helper method, you can check if a date is a holiday either in your controller or view.
Alternatives:
REXML or libxml (I haven’t tried these yet, as hpricot was said to be faster)
References:
Parsing XML with Ruby
Parsing XML quickly
Parse XML with Hpricot
Enjoy
Update:
for xml like this: <date year=”2008″ month=”01″ day=”01″ type=”pulic”>test holiday</date>
you can access it using xml_date.attributes["month"]
HowTo: Virtual Attributes
1) rails howto_use_vitual_attributes
2) cd howto_use_virtual_attributes
3) ruby script/generate scaffold Person first_name:string last_name:string
4) rake db:migrate
5) open up person.rb and add these getter and setter methods
def full_name
[first_name, last_name].join(' ')
enddef full_name=(name)
split = name.split(' ', 2)
self.first_name = split.first
self.last_name = split.last
end
6) edit your new.html.erb file
<%= f.label :full_name %>
<%= f.text_field :full_name %>
Note: full_name is not in the db, it’s just a virtual attribute
7) ruby script/server
localhost:3000/people/ (note: not persons
)
Based on Railscasts ep16.
HowTo: RESTful Autocomplete
rails 2.1
1) rails howto_auto_complete
2) cd howto_auto_complete
3)
ruby script/generate scaffold Tag name:string
4)
ruby script/generate scaffold Post title:string body:text tag_id:integer
5)
rake db:migrate
6) test if it works, add data if you want
ruby script/server
7)
ruby script/plugin install auto_complete
in tag controller index replace with this:
@tags = Tag.find(:all, :conditions => ['name LIKE ?', "%#{params[:search]}%"])
9) in posts.rb put these methods:
belongs_to :tagdef tag_name
tag.name if tag
enddef tag_name=(name)
self.tag = Tag.find_or_create_by_name(name) unless name.blank?
end
10) create an index.js.erb in views/tags:
<%= auto_complete_result @tags, :name %>
(restart server to check http://localhost:3000/tags.js)
11) put this in the forms where you want autocomplete (I put mine in edit and new):
<%= text_field_with_auto_complete :post, :tag_name, { :size => 15 }, { :url => formatted_tags_path(:js), :method => :get, :with => "'search=' + element.value" } %>
12) add in layouts/posts.html.erb:
<%= javascript_include_tag :defaults %>
Notes:
-based on Railcasts episode 102
-since post belongs to tag, the postcontroller magically gets/adds the tag name through the set and get methods in #9, the tag_id is still the one saved in posts table