Posts

Showing posts with the label rails

Making Will Paginate Ajax + Rails 3

1. Create a helper file : app / helpers / remote_link_pagination_helper.rb module RemoteLinkPaginationHelper   class LinkRenderer < WillPaginate::ActionView::LinkRenderer     def link(text, target, attributes = {})       attributes['data-remote'] = true       super     end   end end 2. In the View File where pagination links come, add this line. (@people is the array to paginate) will_paginate @people, :renderer => 'RemoteLinkPaginationHelper::LinkRenderer' Now the links must work with Ajax

Will Paginate Ajax pagination

I have gone through many articles on how to use Ajax pagination with will_paginate. Here is how i did & it worked for me, Step 1 : Create a helper called remote_link_renderer.rb and use the following code, class RemoteLinkRenderer < WillPaginate::LinkRenderer def prepare(collection, options, template) @remote = options.delete(:remote) || {} super end protected def page_link(page, text, attributes = {}) @template.link_to_remote(text, {:url => url_for(page), :method => :get}.merge(@remote), attributes) end end Step 2: Make the view file table in a partial(_units.html.erb), <div id="units"> <%= render :partial => "units" %> </div> Step 3 : And in the partial _units.html.erb add will paginate code, <%= will_paginate @units, :renderer => 'RemoteLinkRenderer' , :remote => { :update => 'units'} %> Step 4 : In the controller use: respond_to do |format| format.js { render :partial =...

Auto Complete Text Box in Rails

Image
Found an Awesome plugin https://github.com/rails/auto_complete for doing this and i made it in 5-10 mins. Install plugin : ruby script/plugin install git://github.com/rails/auto_complete.git Use in HTML for Text field: <%= text_field_with_auto_complete 'phonenumber', 'to',{}, :skip_style => false %> Controller : skip_before_filter :verify_authenticity_token, :only => [:auto_complete_for_phonenumber_to] def auto_complete_for_phonenumber_to phonenumber = params[:phonenumber][:to] @phones = CustomerPhone.phonenumber_search(phonenumber) render :partial => 'phonenumbers' end Search Query in model: def self.phonenumber_search(keyword) find(:all, :conditions=>["phonenumber like ?", "%#{keyword}%"]) end View : Create Partial : "_phone_number.html.erb" <%= auto_complete_result @phones, :phonenumber %> Restart your Server & Search. It works. Note : If you get undefined method...

Rails find_by_sql returns object ??

you can use this, ActiveRecord::Base.connection.select_value("sql query")

select box Send Id, display name..

Hi, used this to send the ID in params & display name in the select box. select_tag "user", options_from_collection_for_select(User.all, :id, :name) For adding option & showing selected params, select_tag "user_id", "<option>select one</option>" + options_from_collection_for_select(User.all, :id, :name, params[:user_id].to_i) -- sri.

You are being redirected

Hi, I have got this page "You are being redirected", whenever i used redirect. I found out that I have written methods such as redirect_XXX, redirect_yyy. I have changed the method names & it works !! Not using the rails keywords as method names, stops this bug.. Thanks, Srikanth

Making a http/https post request

Spent an hour to find out how to send a https post request and this is how .. require 'rubygems' require 'net/http' require 'net/https' require 'uri' http = Net::HTTP.new('facebook.com', 443) http.use_ssl = true path = "/oauth/access_token" data = 'id=123456' resp, data = http.post(path, data) puts resp.inspect puts data.inspect

You’re in the middle of a conflicted merge (git)

Problem Trying to update (pull) in git causes the error ‘you’re in the middle of a conflicted merge’. How to resolve a Git Conflict?  Solution NOTE: Take a backup of your code before you do this. This will remove all your changes and revert to master branch!! To be able to get out of this error try the followng: git reset --hard HEAD git fetch origin git reset --hard origin to reset the state, and then you should be able to use git pull as normal. This site helped me when i faced this problem - http://www.42.mach7x.com/2009/11/24/youre-in-the-middle-of-a-conflicted-merge-git/

Generate random texts

Hi, I have used this method to generate random texts .... def rendom_password chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a newpass = "" 1.upto(7) { |i| newpass end Thanks, sri

Adding GEM sources

sudo gem sources -a http://gems.github.com/ sudo gem sources -a http://gems.rubyonrails.org/

Adding data in add column

Adding data in add column class AddPeopleSalary def self.up add_column :people, :salary, :integer Person.reset_column_information Person.find(:all).each do |p| p.update_attribute :salary, SalaryCalculator.compute(p) end end end

Amazon simple Payment in ruby on rails

hi, Amazon is Doing a great job in rails Payments. here is the ruby code for generation of button. require 'base64' require 'openssl' module PayNowWidgetUtils def generate_signed_form(access_key, aws_secret_key, form_params) form_params['accessKey'] = access_key str_to_sign = "" form_params.keys.sort.each { |k| str_to_sign += "#{k}#{form_params[k]}" } digest = OpenSSL::Digest::Digest.new('sha1') hmac = OpenSSL::HMAC.digest(digest, aws_secret_key, str_to_sign) form_params['signature'] = Base64.encode64(hmac).chomp signed_form = STARTFORM form_params.each do |key, value| next unless key and value signed_form += FORMELEM end signed_form += ENDFORM...

check whether an url is working or not..

1. For domains: ping "domain name" 2. For urls, use the following.. def check_valid_link(link_url) retrycount = 0 begin res = Net::HTTP.get_response(URI.parse(link_url)) if res.code =~ /2|3\d{2}/ return true else return false end rescue Timeout::Error if retrycount retrycount += 1 sleep 3 retry else return false end rescue return false end end

image science requirement

.ruby_inline/Inline_ImageScience_aa58.c:2:23: error: FreeImage .h: No such file or directory getting such an error?? just install freeimage, http://www.urbanpuddle.com/articles/2008/01/22/install-freeimage-imagescience-on-ubuntu-gutsy#comments the above link will guide u in installing.. thanks,

calling JS from form in rails

"report"},{:method => :post, :onSubmit => "return isNumeric(document.getElementById('premium_user'))"})%>

CSV

hi, any work under csv?? here s something interesting which makes ur csv work easier. http://fastercsv.rubyforge.org/ Thanks.

Weekday or not

hi, wanna find whether a day is week day or not?? i have tried tht here. , date=date.today [0,6].include?(date.wday) ------------------------------------------------------------------------ require 'date' class Date def weekend? self.wday == 0 || self.wday == 6 end end d1 = "9 December 2008" d2 = "13 December 2008" p Date.parse(d1).weekend? # false p Date.parse(d2).weekend? # true ------------------------------------------------------------------------ I have used the code for calculation of weekdays between 2 dates., require 'date' d1 = Date.new( 2008, 11, 1 ) d2 = Date.new( 2008, 12, 31 ) WEEKDAY_NUMBERS = [1,2,3,4,5] weekdays = (d1..d2).select{ |d| WEEKDAY_NUMBERS.include?( d.wday ) } p weekdays.length ----------------------------------------------------

Displaying Rss in rails

hi, i have displayed an array as rss feeds, using rails.. here s the code.. In the controller, h={} h[:summary] =summary h[:description]=description h[:dtstart]=dtstart.to_s h[:url]=url @arr render :layout =>false response.headers["Content-Type"]= "application/xml; charset=utf-8" In the View file., Filename is , *.rxml xml.instruct! xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do xml.channel do |feed| feed.title("My great blog!") feed.description("description") feed.link("ur url link") @arr.each { |p| feed.item do |item| item.title p[:summary] item.description p[:description] item.link p[:url] item.pubdate p[:dtstart] end } end end now it is displayed as xml feed in the view file.. Thanks .

ICAL - specifications

hi, here is the ical specifications listed by wiki.. http://upload.wikimedia.org/wikipedia/en/c/c0/ICalendarSpecification.png Thanks.

google page rank gem

hi.. Ruby has this gem, to find google page rank of a site......, just install the gem. >>> sudo gem install googlepagerank >>> example program: require "rubygems" require "googlepagerank" puts GooglePageRank.get("www.yahoo.com") => 9 u can check the above in the site, for further info. http://googlepagerank.rubyforge.org/ thanks..