768x90 Getting Online Shouldn't be Tough- $7.49 .com Domains at Go Daddy

How to use find_by_sql without Model

many cases, we use model to use find_by_sql like ModelName.find_by_sql, but now how we can find_by_sql without mode?

ActiveRecord::Base.connection.execute 'select * from users'

To return array of hashes, you can use it :

ActiveRecord::Base.connection.select_all

.


Translation for your Ruby on Rails App



I am writing this article with accompanied by a cup of coffee while waiting MU Vs Chealsea for Champion Final. Back to the topic. You should know many familiar online translation like google and altavista. Now i will like to introduce you about gibberish in rails. Let start it :

  • Install the plugin to your app rails.
ruby script/plugin install http://svn.myutil.com/projects/plugins/gibberish_rails/
or
ruby script/plugin install svn://errtheblog.com/svn/plugins/gibberish
  • After that go to your Application_controller.rb then use arround_filter for implementation of gibberish :
class ApplicationController < ActionController::Base
around_filter :set_language

private
def set_language
Gibberish.use_language(session[:language]) { yield }
end
end
  • Another method is described in README file. Like :
class ApplicationController < ActionController::Base
around_filter :use_best_guess_locale

private
def use_best_guess_locale
session[:locale] = GibberishRails.best_guess_locale(params[:locale], request.env['HTTP_ACCEPT_LANGUAGE']) if ( ! session[:locale] || params[:locale] || RAILS_ENV == 'development' )

Gibberish.use_language(session[:locale]) {yield}
end
end
  • To create new dictionary, you can create it in YAML file such as es.yaml :
welcome_friend: ¡Recepción, amigo!
welcome_user: ¡Recepción, {user}!
love_rails: Amo los carriles.



_

Simple & Awesome Rails Form

How to create Simple, fast and awesome rails form in your rhtml or html.erb ? the answer for now is Super_In_Place_Controls & I tested in Rails 2.0. Let start to use it :

  • Install the plugin to your ruby app
ruby script/plugin install http://os.flvorful.com/svn/plugins/super_in_place_controls

  • In your layout or rhtml / html.erb put it :
<%= stylesheet_link_tag 'in_place_styles' %>

  • Done !!, let start to implement it in your view file (click the image below to enlarge).
  • For regular text_field you can change it to be :
in_place_text_field :product, :title

  • For regular text_area, you can change it to be :
in_place_text_area :product, :description

  • For regular select_tag, you can change it to be:
in_place_select :product, :product_type, :choices => %w(Awesomeness Coolness Phatness RubyBliss).map { |e| [e, e] }

  • For regular radio_collection, you can change it to be :
in_place_radio :product, :price, :choices => %w(199 299 399 499 599 699 799 899 999).map { |e| [e, e] }

  • For check box collection you can change it to be:
in_place_check_box :product, :category_ids, :choices => Category.find(:all).map { |e| [e.id, e.title] }, :display_text => :collection

  • And for date you can change to be :
in_place_date_select :product, :display_begin

  • for more style you can addcalendar_date_select_includes "blue" to the pages you want to use the calendar select on. The other styles for the calendar_date_select are "blue", "plain", "red", "silver", "default".

Create Realtime World News in Your Site

What could you do if you had access to the world’s news, and had a standardized and rational way to get quick responses to rich queries about what’s happening in the world? What could you build if you could incorporate dynamic, global, continually refreshed, high quality content into your applications, widgets, and websites? You should have many answers. But I have only 1 act, I will smileproudly. :D. Let's start to implement it by using Ruby on Rails:

  • Download this code and paste it to your app_name/lib folder
  • Then in your controller, put it :
require 'daylife'
a = Daylife::API.new('your api key','sharedsecret')
r = a.execute('search','getRelatedArticles', :query => 'sam adams', :limit => 5)
if(r.success?)
r.articles.each {|a| puts a.headline }
puts r.articles[1].source.daylife_url
else
# output the error message
puts "Error: #{r.code}: #{r.message}"
end
  • Now your dream comes true to have site like Yahoo News or at least like daylife.com
  • Has been tested and working nice :D

Snapshot Web Page trough Ruby

Some times, newbie question is valuable for me. Thanks for some one who asked about Snapshot a webpage in ruby by providing web url. Let see it :

  • Sign Up a free account HERE
  • Get Your API Key, after logged in.
  • Create a New File in your Model with name snapweb.rb, than paste code below inside :
require 'net/http'
require 'rubygems'
require 'xmlsimple'

class Snapweb

@@api_baseurl = 'http://webthumb.bluga.net/api.php'
@@api_key = 'fc52f8bdb9e5b86f8150a145d5c8fd97'

attr_accessor :collection_time, :job_id, :ok

def initialize(url, width = 1024, height = 768)
#for safety url you can uncomment it :
#url = url.gsub(/&/, '& a m p ;')
#please delete space in '& a m p ;'

api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><request><url>#{url}</url><width>
#{width}</width><height>#{height}</height></request></webthumb>}

result = do_request(api_request)

if result.class == Net::HTTPOK
result_data = XmlSimple.xml_in(result.body)
@job_id = result_data['jobs'].first['job'].first['content']
@collection_time = Time.now.to_i + result_data['jobs'].first['job'].first['estimate'].to_i
@ok = true
else
@ok = false
end
end

def retrieve(size = :small)
api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><fetch><job>#{@job_id}</job><size>
#{size.to_s}</size></fetch></webthumb>}
result = do_request(api_request)
result.body
end

def retrieve_to_file(filename, size = :small)
File.new(filename, 'wb+').write(retrieve(size.to_s))
end

def ready?
return unless Time.now.to_i >= @collection_time

api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><status><job>#{@job_id}</job></status></webthumb>}
result = do_request(api_request)

if result.class == Net::HTTPOK
@ok = true
result_data = XmlSimple.xml_in(result.body)
begin
@result_url = result_data['jobStatus'].first['status'].first['pickup']
@completion_time = result_data['jobStatus'].first['status'].first['completionTime']
rescue
@collection_time += 60
return false
end
else
@ok = false
end

true
end

def ok?
@ok == true
end

def wait_until_ready
sleep 1 until ready?
end

private

def do_request(body)
api_url = URI.parse(@@api_baseurl)
request = Net::HTTP::Post.new(api_url.path)
request.body = body
Net::HTTP.new(api_url.host, api_url.port).start {|h| h.request(request) }
end
end

  • After that in your controller, put it :

class TeapociController < ApplicationController

def index

web_pict = Snapweb.new("http://teapoci.blogspot.com")

if web_pict.ok?
web_pict.wait_until_ready web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_1.jpg", :small)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_2.jpg", :medium)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_3.jpg", :medium2)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_4.jpg", :large)

flash[:notice] = "Thumbnails saved"

else
flash[:notice] = "Error"
end

end
end

  • Now you have the screenshot images at folder /public/images/

Enjoy & Good Luck!!!

Thanks to : Josh

Live Validation Field with AJAX

LiveValidation is a small open source javascript library for making client-side validation quick, easy, and powerful. It comprises of two main parts. Firstly, it provides developers with a rich set of core validation methods, which can also be used outside the context of forms. Secondly, it provides your visitors with real-time validation information as they fill out forms, helping them to get it right first time, making the forms easier, quicker and less daunting to complete.

The naming conventions and parameters of the validations are similar to those found in the Ruby on Rails framework, and as such is the perfect client-side companion. Don’t worry if you dont use Ruby on Rails though, LiveValidation can be used anywhere you like, is simple to learn, and a joy to use.

Two versions are provided - a prototype.js version (ideal for use with Rails), and a standalone version (for using with any other javascript framework, or when having one at all would be overkill). Both are fully tested on most modern browsers with a comprehensive test suite.

So take a look around, download it, and make some forms (for) fun!

Check this out : LIVEVALIDATION.com

Random Characters in Ruby on Rails

  • AlphaNumeric Random Characters
>> chars = ("a".."z").to_a + ("1".."15").to_a
>> newpass = Array.new(8, '').collect{chars[rand(chars.size)]}.join
>> "8xa2b13f"

  • Another AlphaNumeric Random Characters
>> (1..8).map{ (0..?z).map(&:chr).grep(/[a-z\d]/i)[rand(62)]}.join
>> "JH789gfd"

  • ASCII Random Characters
>> (0..5).inject('') { |r, i| r << rand(93) + 33 }
>> "S#;og^"


Date and Time Functions in Ruby on Rails

This is implementation of Date and Time in Database (MySQL) into Ruby on Rail

Example:

BillPay.find(:all, :order => 'weekday(paid_at)' )
BillPay.find(:all, :select => 'day_of_year(paid_at) as "Days" ' )



Name Description
ADDDATE()(v4.1.1) Add dates
ADDTIME()(v4.1.1) Add time
CONVERT_TZ()(v4.1.3) Convert from one timezone to another
CURDATE() Return the current date
CURRENT_DATE(), CURRENT_DATE Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME Synonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP Synonyms for NOW()
CURTIME() Return the current time
DATE_ADD() Add two dates
DATE_FORMAT() Format date as specified
DATE_SUB() Subtract two dates
DATE()(v4.1.1) Extract the date part of a date or datetime expression
DATEDIFF()(v4.1.1) Subtract two dates
DAY()(v4.1.1) Synonym for DAYOFMONTH()
DAYNAME()(v4.1.21) Return the name of the weekday
DAYOFMONTH() Return the day of the month (1-31)
DAYOFWEEK() Return the weekday index of the argument
DAYOFYEAR() Return the day of the year (1-366)
EXTRACT Extract part of a date
FROM_DAYS() Convert a day number to a date
FROM_UNIXTIME() Format date as a UNIX timestamp
GET_FORMAT()(v4.1.1) Return a date format string
HOUR() Extract the hour
LAST_DAY(v4.1.1) Return the last day of the month for the argument
LOCALTIME(), LOCALTIME Synonym for NOW()
LOCALTIMESTAMP, LOCALTIMESTAMP()(v4.0.6) Synonym for NOW()
MAKEDATE()(v4.1.1) Create a date from the year and day of year
MAKETIME(v4.1.1) MAKETIME()
MICROSECOND()(v4.1.1) Return the microseconds from argument
MINUTE() Return the minute from the argument
MONTH() Return the month from the date passed
MONTHNAME()(v4.1.21) Return the name of the month
NOW() Return the current date and time
PERIOD_ADD() Add a period to a year-month
PERIOD_DIFF() Return the number of months between periods
QUARTER() Return the quarter from a date argument
SEC_TO_TIME() Converts seconds to 'HH:MM:SS' format
SECOND() Return the second (0-59)
STR_TO_DATE()(v4.1.1) Convert a string to a date
SUBDATE() When invoked with three arguments a synonym for DATE_SUB()
SUBTIME()(v4.1.1) Subtract times
SYSDATE() Return the time at which the function executes
TIME_FORMAT() Format as time
TIME_TO_SEC() Return the argument converted to seconds
TIME()(v4.1.1) Extract the time portion of the expression passed
TIMEDIFF()(v4.1.1) Subtract time
TIMESTAMP()(v4.1.1) With a single argument, this function returns the date or datetime expression. With two arguments, the sum of the arguments
TO_DAYS() Return the date argument converted to days
UNIX_TIMESTAMP() Return a UNIX timestamp
UTC_DATE()(v4.1.1) Return the current UTC date
UTC_TIME()(v4.1.1) Return the current UTC time
UTC_TIMESTAMP()(v4.1.1) Return the current UTC date and time
WEEK() Return the week number
WEEKDAY() Return the weekday index
WEEKOFYEAR()(v4.1.1) Return the calendar week of the date (1-53)
YEAR() Return the year
YEARWEEK() Return the year and week

link_to_file - Call File from .rhtml or .html.erb


  • Open app/helpers/application_helper.rb
  • Paste it :
def link_to_file(name, file, *args)

if file[0] != ?/
file = "#{@request.relative_url_root}/#{file}"
end

link_to name, file, *args

end

  • In your view, put it:
<%= link_to_file "teapoci file here", "teapoci.php" %>
.


 
powered by Blogger