How to solve error “couldn’t parse YAML”
Posted by eve in general web on June 18, 2012
When I set up new project, and try to run ‘rake db:migrate’, I get the following error :
rake aborted! couldn't parse YAML at line 16 column 15
The quick and dirty solution is:
Put this code on config/boot.rb :
require 'yaml' YAML::ENGINE.yamler = 'syck'
How to clear upload file input field
Posted by eve in ruby on rails on April 23, 2011
When I created upload multi files feature, I faced into the problem. The problem is about how to clear the file input field after we has uploaded one file and then we want to upload the second file. Curiously, the problem is only on IE. I have searched and researched any ways but I can’t get the solution. Many resources said that there is no access to value field of file input tag because of security restriction. However, I believe there is a trick. So, what trick is it?
I found two resources that inspiring me to solve this problem, Clear upload file input field with jQuery and Clear upload file input field. I modified the ways to be suitable with my application needed.
Here’s the html code :
<div id="file_input_container"> <%= file_field :image, :image, :size => "15" %> </div>
Also, I have link tag “Add Photo”. When the link clicked, it will clear the file input file.
<%= link_to_function "Add Photo", "reset_image_field_html();" %>
This is the javascript code:
function reset_image_field_html() {
$('#file_input_container').html($('#file_input_container').html());
}
That’s all.
How to validate image dimension in paperclip ?
Posted by eve in ruby on rails on April 2, 2011
I use paperclip gem, v2.3 from https://github.com/thoughtbot/paperclip/tree/master. The problem that I found on using this gem is how to validate image dimension. It seems that plugin doesn’t have method to validate image dimension. Is there an easy way to validate image dimension in paperclip?
There are two gem alternatives to achieve the objective. First alternative, using gem from https://github.com/eugenebolshakov/paperclip, you will find method for validating image dimension. Just put this code on the model :
validates_attachment_dimensions :image, :minimum =>; 300, :maximum => 900
However, I haven’t tested whether it works or not. I prefer with the second gem, which I got from https://github.com/thoughtbot/paperclip/tree/master.
These are the steps of how you setup your project to use that gem to validate your uploaded image dimension :
1) Create module in the config/initializers to get width and height of an image:
module Paperclip
class Attachment
def width(style = "origina"l)
Paperclip::Geometry.from_file(queued_for_write[style]).width unless queued_for_write[style].blank?
rescue
nil
end
def height(style = "original")
Paperclip::Geometry.from_file(queued_for_write[style]).height unless queued_for_write[style].blank?
rescue
nil
end
end
end
2) Define custom validate method on the model:
validate :check_image_dimension
def check_image_dimension
width = self.try(:avatar).try(:width)
height = self.try(:avatar).try(:height)
if (width.to_i < 140 || height.to_i < 140)
self.errors.add(:avatar, "The selected file could not be uploaded.
The image is too small, the minimum dimensions are 140x140 pixels.")
end
end
Done. 🙂
How to implement the dynamic authorization with CanCan ?
Posted by eve in ruby on rails on April 2, 2011
I have used CanCan plugin to manage authorization on my rails app, but it’s still static authorization. I just create code like this:
def initialize(user)
if user.admin?
can :manage, :all
else
can :read, :all
end
end
My app is getting bigger. There are users with many user types. Every user type has different role / authorization. I’d like to create a feature that user admin can manage authorization for all user types. Admin can assign or remove the permission to each user types. So, what should I do to implement that feature? Read the rest of this entry »
How to exclude unnecessary files in rcov on cucumber ?
Posted by eve in ruby on rails on April 2, 2011
I write cucumber test and do the coverage analysis with rcov. This is my rcov look like :
I want to exclude the unnecessary files, eg. files on /.bundler directory. So, the solution is:
Find the rcov config “lib/tasks/cucumber.rake”, and write on the rcov_opts what the files that you want to exclude. For example
Cucumber::Rake::Task.new({:ok => ['coverage_setup', 'db:test:prepare']}, 'Run features that should pass') do |t|
t.binary = vendored_cucumber_bin
t.fork = true
t.profile = 'default'
t.rcov = true
t.rcov_opts = %w{--rails --aggregate coverage.data --exclude osx\/objc,gems\/,spec\/,\.bundler\/,features\/}
end
That’s all.
Can sortable_table plugin do order by multiple columns ?
Posted by eve in ruby on rails on February 22, 2011
I’m using sortable_table plugin for sorting html table in rails app.
I want to sort the html table by multiple columns.
For example (sort by brands.title and models.title) :
select distinct brands.title as brands, models.title as model
from brands, models
where
brands.id = models.brand_id
order by brands.title desc, models.title desc
I put this code on controller:
sortable_attributes :brand_model => "brands.title, models.title"
However, it reproduces wrong sql syntax, like this:
select distinct brands.title as brands, models.title as model
from brands, models
where
brands.id = models.brand_id
order by brands.title, models.title desc
So it means sort by brands.title asc, models.title desc (brands.title always asc).
What can I do with sortable_table plugin so I can sort it by multiple columns?
Hmm.. finally I got the solution. Just put sortable_attributes on controller as array.
sortable_attributes :brand_model => [“brands.title”, “models.title”]
It will generate order syntax like this:
order by brands.title desc, models.title desc
or
order by brands.title asc, models.title asc
That’s all.
How to ignore updated_at field on database ?
Posted by eve in ruby on rails on February 21, 2011
Is it posible to ignore updated_at field on database in order not to change? I have some fields on a table on database, called them: id, title, description, status (1,2,3), created_at, updated_at. I want the updated_at field is stop working when I change title or description field. So I can know when last status changed by viewing updated_at field.
I know that I can solved that by adding new field, say that “change_status_at”. Everytime the status field changed, change_status_at field is changed too. However, I’ve ever got the problem that I think it’s more elegant if I can make the auto-increment updated_at field stop for a while instead of I create a new field to record the date like “change_status_at” field. I just want to know is there a way to do it..
There is my solution:
I tried this code, and it works well.
Create module in initializers :
module ActiveRecord
class Base
def update_attributes_without_timestamping(attr = {})
class << self
def record_timestamps; false; end
end
update_attributes(attr)
class << self
def record_timestamps; super ; end
end
end
end
end
Everytime you want to update fields without update updated_at field, just call ‘update_attributes_without_timestamping()’.
Example:
>> user = User.find :first
>> user.update_attributes({:updated_at => 100.years.ago})
=> true
>> user.updated_at
=> Mon, 21 Feb 2011 05:33:20 CET +01:00
>> user.update_attributes_without_timestamping({:updated_at => 100.years.ago})
=> nil
>> user.updated_at
=> Tue, 21 Feb 1911 05:33:46 CET +01:00
Just tell me if you have a much better solution.
Thanks.
How to create CDATA node on Nokogiri ?
Posted by eve in ruby on rails on February 21, 2011
I have a problem to create CDATA node on Nokogiri. I use create_cdata(), it’s a nokogiri function, but it failed.
This is my code:
tmp = Nokogiri::XML::Document.new child = Nokogiri::XML::Node.new key, output child.content = tmp.create_cdata(value) parent.add_child(child)
It generates xml like this:
<key> <![CDATA[some values, some values]]> </key>
What’s wrong with the code?
After I figure it out some minutes, I found what’s the wrong.
The code must be modified to be:
tmp = Nokogiri::XML::Document.new
parent.add_child("<#{key}>#{tmp.create_cdata(value)}</#{key}>")
So, it will generate the right CDATA node:
<key> <![CDATA[some values, some values]]> </key>
How to create an upload feature for external video (like youtube) and the player for that video ?
Posted by eve in ruby on rails on January 30, 2011
I have a form to upload video from local directory. I use paperclip and acts as state machine for converting the video. I want to add a new feature to my application, the feature is the application can upload video from external link (like youtube, etc) too. I was thinking so simple, just add ‘external_url’ column to videos table to save the external video link.
The problem that I found, how the application can display the thumbnail of external video link and if the thumbnail clicked, the video can be played. I have used jquery-oembed plugin, but the plugin only for changing the link becomes the script to embed video, I need to display the video thumbnail too.
There is an easy way. I use acts as unvlogable plugin. This plugin provide the functions that I need.
First, install the plugin.
script/plugin install git://github.com/mamuso/acts_as_unvlogable.git
And don’t forget to install gems: youtube-g, xml-simple and hpricot. The plugin need them.
To display the video thumbnail:
videotron = UnvlogIt.new(video.external_url) link_to image_tag(videotron.thumbnail), :action => "view_video_answer", :id => video.id
To play the video:
videotron = UnvlogIt.new(video.external_url) videotron.embed_html(360, 240)
Let’s practice !
Create the javascript countdown
Posted by eve in ruby on rails on January 30, 2011
I’d like to create a CRUD application for “answer a question”.
The edit feature need a countdown function.
User can edit his answer within 100 seconds after the answer is made.
All answers are displayed, and the countdown should be displayed too for each answer.
These are the steps:
- On the page that displayed all answers, every answer must have render partial to time_left_section.
- On the _time_left_section.html.erb, the countdown function must be defined.
<% if (Time.now - answer.created_at).round <= 100 %>
<div>
<%= link_to "", edit_answer_path(
{:id => @<a rel="nofollow" href="/users/question">question</a>.id,
:answer_id => answer.id}),
{:id => "time_left_#{answer.id}"} %>
</div>
<script type="text/javascript">
var milisec_<%= answer.id %> = 0;
var seconds_<%= answer.id %> =<%=100-(Time.now-answer.created_at).round%>;
function display_<%= answer.id %>(){
var obj = document.getElementById("<%= "time_left_#{answer.id}" %>");
if(seconds_<%= answer.id %> >= 0) {
if(milisec_<%= answer.id %><=0) {
milisec_<%= answer.id %>=9; seconds_<%= answer.id %>--
}
else
milisec_<%= answer.id %>--;
obj.innerHTML = "Edit within "+ seconds_<%= answer.id %> +" seconds";
setTimeout("display_<%= answer.id %>()",100);
}
else obj.innerHTML = ""
}
window.setTimeout('display_<%= answer.id %>()',100);
</script>
<% end %>
That’s all.. 🙂
