by sandipransing
Methods defined in Helper modules can directly accessed in rails views because this is what they are pretended for but we often come across with situations where we wanted to use some helper methods in controllers, views, models and mailers and obvious we don't want to repeat same lines of code everywhere which also rail does not permit. forgotten DRY? Oh then how to do achieve same without violating rails principle.
Certainly there are ways to do this ..
1. Helper methods all the time for views
class ApplicationController < ActionController::Base
helper :all# include all helpers, all the time for views
end
2. Controller methods in views
class ApplicationController < ActionController::Base
helper_method :current_store
#now controller_method can be accessed in views
end
2. Helper methods in controller
class ApplicationController < ActionController::Base
include ActionView::Helpers::ApplicationHelper
end
3. Helper methods in model
class Student < ActiveRecord::Base
include ActionView::Helpers::ApplicationHelper
end
4. Helper methods in mailer
class Notifier < ActionMailer::Base
add_template_helper(ApplicationHelper)
#...
end
Read More…
by sandipransing
To Add custom conditions to authlogic finders first of all we need to override authlogic find_by_login method.
class UserSession < Authlogic::Session::Base
after_validation :check_if_verified
find_by_login_method :find_by_login_and_deleted_method
end
Then we need to define overridden method inside User model
class User < ActiveRecord::Base
acts_as_authentic
def self.find_by_login_and_deleted_method(login)
find_by_email_and_deleted(login, false)
end
end
got easy..wooooooo :)
Read More…
by sandipransing
requirement was to display decimal numbers which are having scale values present to be displayed in decimal format otherwise display them as integer.
Output expected
12.23 => 12.23
12.00 => 12
While rendering any object on html page by default "to_s" method gets executed.
So, i overwrote "to_s" method of BigDecimal class as below.
Anyone having better solution. Please reply with your solutions. Many thanks!
Put below code in file "config/intializers/core_extensions.rb"
class BigDecimal
alias :old_s :to_s
def to_s
return to_i.to_s if eql? to_i
self.old_s
end
end
Read More…
by sandipransing
On linux machine following settings needs to be done in order to get in browser calling enabled
for phone numbers.
Installation setup
1. Install twinkle setup (Create user profile) and get it working for outgoing and incoming calls
2. Install telify add-on (can be un-installed once completed with all settings)
3. Copy wrapper script twinkle_tel) click here to download and copy it to "/usr/bin" on user's machine (make sure it has executable permissions)
4. In Firefox go to "preferences/applications"
5. Search for "tel" protocol and change value of tel protocol to "/usr/bin/twinkle_tel"
Usage/ Pre-requisites
HTML source code of phone number should like as below
1. Dialing source code
<a title="phone number" class="telified" nr="9860648108" href="tel:9860648108">9860648108</a>
2. Call disconnect source code
<a title="disconnect call" class="telified" href="tel:disconnect">Disconnect</a>
Read More…
by sandipransing
Delayed Job provides send_later and send_at as instance as well as class_methods methods along-with handle_asynchronously as class method to be written inside class
module Delayed
module MessageSending
def send_later(method, *args)
Delayed::Job.enqueue Delayed::PerformableMethod.new(self, method.to_sy m, args)
end
def send_at(time, method, *args)
Delayed::Job.enqueue(Delayed::PerformableMethod.new(self, method.to_sy m, args), 0, time)
end
module ClassMethods
def handle_asynchronously(method)
aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1
with_method, without_method = "#{aliased_method}_with_send_later#{pu nctuation}", "#{aliased_method}_without_send_later#{punctuation}"
define_method(with_method) do |*args|
send_later(without_method, *args)
end
alias_method_chain method, :send_later
end
end
end
end
Usage of send_later, send_at and handle_asynchronously
# instance method
user.send_later(:deliver_welcome)
# class_method
Notifier.send_later(:deliver_welcome, user)
Notifier.send_at(15.minutes.from_now, :deliver_welcome, user)
# Inside User class write below line after deliver_welcome method
handle_asynchronously :deliver_welcome
Read More…
by sandipransing
Solution to DelayedJob(DJ) gem server start problem
I had installed delayed_job gem 2.0.3, daemons gem but after staring DJ server it shows daemon started but actually process gets killed automatically.
I performed steps given by Kevin on google group and it worked like charm
Here are the steps:
1) sudo gem sources -a http://gems.github.com
2) sudo gem install alexvollmer-daemon-spawn
3) Move the old daemons delayed job script out of the way -> mv script/delayed_job script/delayed_job.daemons
4) Make this your new script/delayed_job: http://gist.github.com/104314
Try it out again making sure it writes to the tmp/pids directory ok.
My line looks like this:
RAILS_ENV=production script/delayed_job start
then to check (besides running 'ps'), you can run this:
RAILS_ENV=production script/delayed_job status
Read More…
by sandipransing
Array of years using range
((yr=Date.current.year)-9..yr).to_a
#=> [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010]
Array of years using lambda
Array.new(10){|i| Date.current.year-i}
#=> [2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001]
Array of months
Date::MONTHNAMES.compact
#=> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Array of abbreviated months
Date::ABBR_MONTHNAMES.compact
#=> ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
Array of abbreviated months with index (ps. collect_with_index is core extension method added to array)
Date::ABBR_MONTHNAMES.compact.collect_with_index{|m, i| [m, i]}
#=> [["Jan", 1], ["Feb", 2], ["Mar", 3], ["Apr", 4], ["May", 5], ["Jun", 6], ["Jul", 7], ["Aug", 8], ["Sep", 9], ["Oct", 10], ["Nov", 11], ["Dec", 12]]
OR
Date::ABBR_MONTHNAMES.compact.each_with_index.collect{|m, i| [m, i+1]}
#=> [["Jan", 1], ["Feb", 2], ["Mar", 3], ["Apr", 4], ["May", 5], ["Jun", 6], ["Jul", 7], ["Aug", 8], ["Sep", 9], ["Oct", 10], ["Nov", 11], ["Dec", 12]]
Read More…
by sandipransing
1.Install geokit gem
gem install geokit
OR
# Add following line inside rails initialize block
Rails::Initializer.run do |config|
config.gem 'geokit'
end
And then run command
rake gems:install
2. Consider User model with zipcode as attribute field
include Geokit::Geocoders
class User < ActiveRecord::Base
set_table_name :users
validate_presence_of :zipcode
validate :request_zipcode_validation_using_geokit, :if => :zipcode
private
def request_zipcode_validation_using_geokit
# Method request google api for location
# if location found then zipcode is valid otherwise
# add validation error on zipcode field
# as it method contacts with google api and takes time
# to return result, poll request only when zipcode gets
# changed
poll = true # default true for new objects
if self.id ## this means already existing user and zipcode is valid last time
# Hack to find where zipcode got modified or not
# old_user = User.find self.id
poll = false if old_user.zipcode == self.zipcode
end
# Actual requesting api to return location associated with zipcode
if poll
loc = MultiGeocoder.geocode(self.zip_code)
end
# Add Validation Error if location is not found
errors.add(:zip_code, "Unable to geocode your location from zipcode entered.") unless loc.success
end
Please note that same method can also be used to validate state, city and country.
Again we can use combination of fields to validate each other.
Like -
1. Based on country entered, state validation
2. Based on state, city validation
3. Based on city, zipcode validation
or
4. Based on zipcode and country, state and city validation
Here is another method to validate state and city based on zipcode and country.
Lets take example of 'US'
def request_state_and_city_validation_based_on_zipcode
poll = true # default true for new objects
if self.id ## this means already existing user and all attributes were valid last time
# Hack to find any one of location attribute got modified
# old_user = User.find self.id
loc_attrs = %w{zipcode state city} # keep in mind country US is default assumed
if loc_attrs.all? {|attr| self.attribute_for_inspect(attr) == old_user.attribute_for_inspect(attr)}
self.poll = false
end
end
# Actual requesting api to return location associated with zipcode
if poll
loc = MultiGeocoder.geocode("#{self.zip_code}, US")
end
# Add Validation Error if location is not found
unless loc.success
errors.add(:zip_code, "Unable to geocode your location from zipcode entered.")
else
# Validate state and city fields in compare to loc object returned by geocode
errors.add(:state, "State doesn't matches with zipcode entered") if self.state != loc.state
errors.add(:city, "City doesn't matches with zipcode entered") if self.city != loc.city
end
end
Note***
If you are subscriber of blog and not displaying post correctly. I request you to visit post on
blog itself. Somehow style is not getting correctly in email. I will try to fix this problem asap.
Upcoming Posts
1. Geokit finders: Find locations in/within/beyond particular radius from specified location using acts_as_mappable plugin
2. Customizing authlogic for multiple sessions i.e. using different models for role based authentication.
Read More…
by sandipransing
1. Add following line to rails environment file
ActionMailer::Base.delivery_method = :smtp
2. Include your email authentication
Create a ruby file called smtp_settings under config/initializers directory
# config/initializers/smtp_settings.rb
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true,
:user_name => "replies@gmail.com",
:password => "_my_gmail_password_"
}
noTE** Keep starttls_auto always true
3. Create sample mailer in order to ensure that your settings are correct
Create a sample mailer
class EmailMailer < ActionMailer::Base
def test_email
from 'xx@gmail.com'
to 'some@xx.com'
subject "This is test email"
message "It should get delivered to recipient inbox"
end
end
4. Test your configuration
EmailMailer.deliver_test_email
Read More…
by sandipransing
1. Add ActionMailer configuration in environment.
This configuration can be different for development and production.
# Include your application configuration below
# You can set two configurations sendmail as well as smtp
# To use SMTP you need to provide your email account credentials
# Sendmail is a unix package that needs to be installed and configured while
# using sendmail settings
# Chances of getting emails into recipient's inbox are 100% for smtp settings
# whereas sendmail needs some other configurations to be done before using.
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.default_content_type = "text/html"
2. Create Mailer Model and add method to deliver email
class EmailMailer < ActionMailer::Base
def email_with_attachments(email, files=[])
# content type also can be set in environment file as
# ActionMailer::Base.default_content_type = "text/html"
@headers = {content_type => 'text/html'}
@sent_on = Time.now
@recipients = email.recipients
@from = email.from
@cc = FEEDBACK_RECIPIENT
@subject = email.subject
@body = email.message
# attach files
files.each do |file|
attachment "application/octet-stream" do |a|
a.body = file.read
a.filename = file.original_filename
end unless file.blank?
end
end
3. Email Model
# This is the virtual model in rails which has no database table associated with it
class Email < ActiveRecord::Base
# It uses has_no_table plugin to create virtual model
# This can also be done using following lines of code
#
# def self.columns() @columns ||= []; end
# def self.column(name, sql_type = nil, default = nil, null = true)
# columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
# end
#
has_no_table
#insert the names of the form fields here
column :from, :string
column :recipients, :string
column :subject, :string
column :message, :text
column :call_id, :integer
attr_accessor :is_subscribed
#Validations goes here
validates_presence_of :from, :message => "You dont have Email ID, you cannot continue!", :unless => "call_id.blank?"
validates_format_of :from, :with => /^([^@]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i, :unless => "from.blank?"
validates_presence_of :recipients
validates_format_of :recipients, :with => /^([^@]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i, :message => "Invalid email format", :unless => "recipients.blank?"
validates_presence_of :subject, :message
end
4. Usage from console or controller
# Here email is the valid object of email model
# attachments is the area of files to be attached with email
# In my case attachments are of kind of pdf files
# you can specify type of attachment in your mailer method
EmailMailer.deliver_email_with_attachements(email, attachments) if email.valid?
Sending data stream as email attachments in rails.
In some cases, We need to dynamically generate files and you don't want to store them locally on file system instead you always like to email them from memory itself.
Here is the way to do that.
1. Mailer data stream as attachment method
class EmailMailer < ActionMailer::Base
def email_with_data_stream(email, data_stream=[])
@headers = {}
@sent_on = Time.now
@recipients = email.recipients
@from = email.from
@subject = email.subject
@body = email.message
# attach files
data_stream.each do |data|
attachment "application/octet-stream" do |a|
a.body = data[0]
a.filename = data[1]
end unless data_stream.blank?
end
end
end
2. Lets take example of pdf renderer.
# Assume we have object of pdf
attachements = []
data = pdf.render
# Attach as many files you wanted. Be careful about email maximum size ;)
attachments << data
EmailMailer.deliver_email_with_data_stream(email, attachments)
Read More…
by sandipransing
There are almost 4 to 5 simple steps you need to followed before
getting multiple sites working using radiant cms
1. Setup radiant cms
first Install radiant gem
sudo gem install radiant
set 'radiant' under path
export PATH=$PATH:/var/lib/gems/1.8/gems/radiant-0.8.0/bin
Now, we have done with radiant installation.
Let's create new project..
$ radiant multisite -d mysql
$ cd multisite/
Edit database.yml
$ vi config/database.yml
development:
adapter: mysql
database: multisite_development
username: root
password: abcd
host: localhost
Migrations
rake db:create
Run the database bootstrap rake task:
rake db:bootstrap
This task will destroy any data in the database. Are you sure you want
to continue? [yn] yes
...
Create the admin user (press enter for defaults).
Name (Administrator): admin
Username (admin): admin
Password (radiant):
....
Select a database template:
1. Empty
2. Roasters (a coffee-themed blog or brochure)
3. Simple Blog
4. Styled Blog
[1-4]: 2
....
Now we are ready to start
script/server
Open following URL in browser.
http://localhost:3000
You should see site homepage. To manage site goto admin panel.
http://localhost:3000/admin
Now Lets start with multiple sites management
1) Clone multi_site extension into vendor/extensions of your project.
cd vendor/extensions/
git clone git://github.com/zapnap/radiant-multi-site-extension.git multi_site
2) Run the extension migrations.
rake db:migrate:extensions
3) Run the extension update task.
rake radiant:extensions:multi_site:update
4) Restart your server
And we are done with multisite installation, Open following URL in browser.
http://localhost:3000/admin/sites
Add multiple sites as you wanted
Name Domain pattern Base domain name
================================================
site 1 sandip sandip
site 2 gautam gautam
Don't forget to make dns entries in /etc/hosts.
vi /etc/hosts
127.0.0.1 localhost
...
127.0.0.1 sandip
127.0.0.1 gautam
One more, by deault pages created for new sites added are not published.
Please be sure to make them published and modify contents to identify them
Now you can view different sites.
http://sandip:3000
http://gautam:3000
Thats, All
Cheers !
$@ndip
Read More…
by sandipransing
Wrong English is an often problem while developing any website product as
it gives bad view to website user and thus does direct impact on product.
BOSSMan is a ruby gem that interacts with yahoo web service and provides a
simplest way to overcome such errors.
Installation:
gem sources -a http://gems.github.com
gem install jpignata-bossman
Apply and get Application ID from yahoo developer network
URl https://developer.apps.yahoo.com/
Make sure to note it for reference
Usage in ruby app
require 'rubygems'
require 'bossman'
include BOSSMan
BOSSMan.application_id = "Your Application ID here"
Spelling Suggestions
text = BOSSMan::Search.spelling("gooogle")
=> #{"resultset_spell"=>[{"suggestion"=>"google"}], "responsecode"=>"200", "deephits"=>"1", "start"=>"0", "count"=>"1", "totalhits"=>"1"}}>
text.suggestion
=> "google"
More sophisticated way of use -
1. Create a YML file containing list of kewords
2. Load YML file
3. Iterate YML hash to find out spell suggestions
Example: spelling.yml
1 keywords:
2 gooogle:
3 Barack Oabama:
4 Indian:
5 Latuur:
keywords = YAML.load_file('spelling.yml')['keywords'].keys
puts "Correction suggested"
keywords.each do |keyword|
text = BOSSMan::Search.spelling(keyword)
if defined? text.suggestion
puts "#{keyword} => #{text.suggestion}"
end
end
Output
Correction suggested
gooogle => google
Barack Oabama => Barack Obama
Latuur => Latour
Analyze suggestions manually and make neccesary corrections..
Read More…
by sandipransing
Building PDF Document in ruby & rails application using prawn Library
Brief
Before getting started with this tutorial, I would like to thanks Greg and Prawn team for their awesome work towards ruby and rails community.
Installing prawn (core, layout, format, security)
gem install prawn
or
Add following line in rails environment file inside initializer block.
config.gem 'prawn'
Optionally you can specify version to be used and then run task
rake gems:install
Generating pdf using rails console
./script/console
pdf = Prawn::Document.new
It creates new pdf document object. Here you can additionally pass options parameters such as -
Prawn::Document.new(:page_size => [11.32, 8.49], :page_layout => :portrait)
Prawn::Document.new(A0) Here A0 is page size.
Prawn::Document.new(:page_layout => :portrait,
:left_margin => 10.mm, # different
:right_margin => 1.cm, # units
:top_margin => 0.1.dm, # work
:bottom_margin => 0.01.m, # well
:page_size => 'A4')
pdf.text("Prawn Rocks")
=> 12
pdf.render_file('prawn.pdf')
=> #
Here is output file generated [ click]
Now let's go through other goodness of prawn.
pdf = Prawn::Document.new('A3') do
- FONTS [click]
# Specify font to be used or specify path to font file.
font "times.ttf"
font("/times.ttf")
- TEXT [click]
text 'Sandip Ransing', :size => 41, :position => :center, :style => :bold
- STROKE LINE [click]
stroke do
rectangle [300,300], 100, 200
end
- IMAGE [click]
Display Local file system Image
image 'sandip.png', :height => 50, :position => :center, :border => 2
Scale Image
image 'sandip.png', :scale => 0.5, :position => :left
Display Remote image from Internet inside pdf
require "open-uri"
image open('http://t2.gstatic.com/images?q=tbn:kTG6gAKrnou2gM:http://www.facebook.com/profile/pic.php?uid=AAAAAQAQrLXvTWfyY2ANjttV8D1c0QAAAAnDHPFJe0pPFR84iIzXPKro&t=1")
end
- LINE BREAKS
movedown(20)
- TABLE/GRID [click]
data = [
["Name", {:text => 'Sandip Ransing', :font_style => :bold, :colspan => 4 }],
["Address", {:text => 'SHIVAJINAGAR, PUNE 411005', :colspan => 4 }],
["Landmark",{:text => 'NEAR FC COLLEGE', :colspan => 4 }],
["Mobile","9860648108", {:text => "", :colspan => 3 }],
["Education", {:text => "Bachelor in Computer Engineering", :colspan => 4 }],
["Vehicle", 'Hero Honda',"Reg. No.", {:text => "MH 12 EN 921", :colspan => 3 }],
["Additional", "GDCA", "class", 'First', ""],
[{:text => "Areas of Speciality", :font_style => :bold}, {:text => "Ruby, Rails, Radiant, Asterisk, Adhearsion, Geokit, Prawn, ....,...", :font_style => :bold, :colspan => 4}],
[{:text => "Website", :colspan => 2},{:text => "www.funonrails.com", :colspan => 3}],
[{:text => "Company", :colspan => 2},{:text => "Josh Software", :colspan => 3}]
]
table data,
:border_style => :grid, #:underline_header
:font_size => 10,
:horizontal_padding => 6,
:vertical_padding => 3,
:border_width => 0.7,
:column_widths => { 0 => 130, 1 => 100, 2 => 100, 3 => 100, 4 => 80 },
:position => :left,
:align => { 0 => :left, 1 => :right, 2 => :left, 3 => :right, 4 => :right }
- LINKS [click]
link_annotation([200, 200, 500, 40],:Border => [0,0,1], :A => { :Type => :Action, :S => :URI, :URI => Prawn::LiteralString.new("http://twitter.com/sandipransing") } )
link_annotation(([0, 100, 100, 150]), :Border => [0,0,1], :Dest => s"http://funonrails.com")
- PDF Security [click]
encrypt_document :user_password => 'hello', :owner_password => 'railer',
:permissions => { :print_document => false }
- Prawn Inline Formatting
Prawn-format supports inline text formatting that gives user enough flexibility to use html tags.
require 'prawn/format'
text 'This is Strong text', :inline_format => true
text 'This is bold text \n It should be on newline.', :inline_format => true
SAVE PDF File
end
pdf.render_file 'my.pdf'
!!! NOTE: As of time now 'prawn-format' is incompatible with latest prawn gem, It is compatible with prawn version <= 0.6 s
Read More…
by sandipransing
On my development machine, I have rails versions installed ranging from rails 1.2.3 to 2.3
How do i create new rails app that will use rails 2.1.0.
Create new app with rails version 2.1.0
rails _2.1.0_ simple_blog
Specify database to use while creating new rails app
rails _2.1.0_ simple_blog -d mysql
Read More…
by sandipransing
Before getting started with modules and mixins, lets first find out the
need of module & mixins in OOP.
In object oriented programming languages multiple inheritance is basic paradigm (child class extends behavior of base class).
C++ supports multiple inheritance.
Java does support same using interfaces.
In ruby language, multiple inheritance is achieved very easily using mixin
of modules & classes and that makes ruby as powerful language.
Ruby has classes, modules. Modules can be included inside other classes (mixins) to achieve multiple inheritance.
Modules
module Greeting
# here below is the instance method
# and that can be accessed using object of class ONLY
def hi
puts 'Guest'
end
end
Module methods can be called using scope resolution operator (::) or dot operator (.)
Greeting::hi
# => undefined method `hi' for Greeting:Module (NoMethodError)
It is obivous to have an error because we are calling class method and that is not present inside module.
Mixins
Lets include greeting module inside person class
class Person
include Greeting
end
person = Person.new
person.hi #=> "Guest"
Lets see how module methods can be defined. It can be done using either self or class_name.
module Greeting
# here below is the instance method
# and that can be accessed using object of class ONLY
def hi
puts 'Guest'
end
# Below are module methods
# this methods can be invoked
# using Greeting::hi
# OR Greeting.hi
def self.hi
puts 'hi Sandip'
end
# here is one more way to declare
# module methods
def Greeting.bye
puts 'Bye Sandip!'
end
end
Lets invoke methods
Greeting::hi #=> "hi Sandip"
Greeting.bye #=> "Bye Sandip!"
Extending class behavior using modules
class Person
def self.included(base)
base.extend Greeting
end
end
Got easy ?? Cheers!
Read More…
by sandipransing
I am using acts_as_ferret and ferret server as of now with my rails application and it just works fine for me. The ONLY problem is performance as it takes a lot time to build index and to rebuild index when it gets screwed up and that's where sphinx rocks!
To get started with thinking sphinx you need to install sphinx server first.
for installation help click here.
To use sphinx search in rails we need to use either thinking sphinx gem or plugin that can be easily find on github.
Plugin installation
./script/plugin install git://github.com/freelancing-god/thinking-sphinx.git
OR
To install gem run the following command.
gem install thinking-sphinx --source http://rubygems.org/
If you're upgrading, you should read this:
http://freelancing-god.github.com/ts/en/upgrading.html
Successfully installed thinking-sphinx-1.3.16
1 gem installed
Edit environment file and add following lines to it inside initializer block.
config.gem(
'thinking-sphinx',
:lib => 'thinking_sphinx',
:version => '1.3.16'
)
Edit Rakefile and add following lines to it.
require 'thinking_sphinx/tasks'
List rake task that should show up sphinx related tasks.
rake -T ts
(in /home/sandip/v1)
rake doc:plugins:acts_as_audited # Generate documentation for the acts_as_...
rake doc:plugins:acts_as_ferret # Generate documentation for the acts_as_...
rake rails:update:javascripts # Update your javascripts from your curre...
rake rails:update:scripts # Add new scripts to the application scri...
rake stats # Report code statistics (KLOCs, etc) fro...
rake test:units # Run tests for unitsdb:test:prepare / Ru...
rake tmp:sockets:clear # Clears all files in tmp/sockets
rake ts:conf # Generate the Sphinx configuration file ...
rake ts:config # Generate the Sphinx configuration file ...
rake ts:in # Index data for Sphinx using Thinking Sp...
rake ts:rebuild # Stop Sphinx (if it's running), rebuild ...
rake ts:reindex # Reindex Sphinx without regenerating the...
rake ts:restart # Restart Sphinx / Restart Sphinx
rake ts:run # Stop if running, then start a Sphinx se...
rake ts:start # Start a Sphinx searchd daemon using Thi...
rake ts:stop # Stop Sphinx using Thinking Sphinx's set...
rake ts:version # Output the current Thinking Sphinx vers...
Start sphinx server this should give up an error.
rake ts:start
(in /home/sandip/v1)
Failed to start searchd daemon. Check /home/sandip/v1/log/searchd.log.
Adding indexes in models
define_index do
# following fields are database fields
# we can not add model methods in sphinx index
# sphinx fields allows ONLY model based associations
# fields
indexes customer_name
indexes phone
indexes mobile
indexes other_phone
indexes car_make
indexes car_model
indexes registration_no
end
Configure sphinx
rake ts:config
Generating Configuration to /home/sandip/v1/config/development.sphinx.conf
Index sphinx
rake ts:in
(in /home/sandip/v1)
Generating Configuration to /home/sandip/v1/config/development.sphinx.conf
Sphinx 0.9.8-rc2 (r1234)
Copyright (c) 2001-2008, Andrew Aksyonoff
using config file '/home/sandip/v1/config/development.sphinx.conf'...
indexing index 'call_core'...
collected 113521 docs, 2.1 MB
collected 0 attr values
sorted 0.1 Mvalues, 100.0% done
sorted 0.3 Mhits, 100.0% done
total 113521 docs, 2114790 bytes
total 6.102 sec, 346589.68 bytes/sec, 18604.78 docs/sec
distributed index 'call' can not be directly indexed; skipping.
Generating Configuration to /home/sandip/v1/config/development.sphinx.conf
Sphinx 0.9.8-rc2 (r1234)
Copyright (c) 2001-2008, Andrew Aksyonoff
using config file '/home/sandip/v1/config/development.sphinx.conf'...
indexing index 'call_core'...
collected 113521 docs, 2.1 MB
collected 0 attr values
sorted 0.1 Mvalues, 100.0% done
sorted 0.3 Mhits, 100.0% done
total 113521 docs, 2114790 bytes
total 3.628 sec, 582909.70 bytes/sec, 31290.34 docs/sec
distributed index 'call' can not be directly indexed; skipping.
Search using sphinx
./script console
>>Call.search 'sandip'
=> [#, #]
It returns array of records found. conditions are allowed by sphinx. If you need to add conditions on integer attributes then index block in model needs to have has method like author_id in following.
define_index do
indexes content
indexes :name, :sortable => true
indexes comments.content, :as => :comment_content
indexes [author.first_name, author.last_name], :as => :author_name
has author_id, created_at
end
Read More…
by sandipransing
Alias method in ruby
Ruby classes provides a alias_method that can be used to reuse the existing methods.
Consider a situation where you need different methods which has same code and ONLY
they have different names.
In this case alias_method uses suits best choice instead duplicating same code or
writing common method that will get used in all methods, as i did before.
Example, I have methods search, home, index all are doing same functionality.
Old approach
# URL /
def index
list
end
# URL /search
def search
list
end
#URL /home
def home
list
end
private
def list
# code here
end
Correct approach in ruby
def index
# code here
end
alias_method :home, :index
alias_method :search, :index
Attributes aliasing in ruby
Same way one can easily rename existing class attribute names
using alias_attribute method.
alias_attribute(new_name, old_name)
alias_attrinute :username, :login
More practical use
while deprecating attributes, methods in gems, plugins, extensions, libraries always
use aliases in order to maintain backward compatibility.
Got easy ??
that's where ruby rocks !
Read More…
by sandipransing
Install nginx server using following command
apt-get install nginx
Edit nginx configuration and add server block inside html block.
server {
listen 80;
server_name boost;
root /home/sandip/rails_app/public;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
if (-f $request_filename/index.html) {
rewrite (.*) $1/index.html break;
}
if (-f $request_filename.html) {
rewrite (.*) $1.html break;
}
if (!-f $request_filename) {
proxy_pass http://thin;
break;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
Install thin server as gem
sudo gem install thin
Building native extensions. This could take a while...
Building native extensions. This could take a while...
Successfully installed eventmachine-0.12.10
Successfully installed thin-1.2.7
2 gems installed
Install thin service
sudo thin install
Installing thin service at /etc/init.d/thin ...
mkdir -p /etc/init.d
writing /etc/init.d/thin
chmod +x /etc/init.d/thin
mkdir -p /etc/thin
Configure thin to start at system boot
sudo /usr/sbin/update-rc.d -f thin defaults
Then put your config files in /etc/thin
sudo /usr/sbin/update-rc.d -f thin defaults
update-rc.d: warning: thin stop runlevel arguments (0 1 6) do not match LSB Default-Stop values (S 0 1 6)
Adding system startup for /etc/init.d/thin ...
/etc/rc0.d/K20thin -> ../init.d/thin
/etc/rc1.d/K20thin -> ../init.d/thin
/etc/rc6.d/K20thin -> ../init.d/thin
/etc/rc2.d/S20thin -> ../init.d/thin
/etc/rc3.d/S20thin -> ../init.d/thin
/etc/rc4.d/S20thin -> ../init.d/thin
/etc/rc5.d/S20thin -> ../init.d/thin
Create thin configuration
sudo thin config -C /etc/thin/<config-name>.yml -c <rails-app-root-path> --servers <number-of-threads> -e <environment>
</environment></number-of-threads></rails-app-root-path></config-name>
In my case,
sudo thin config -C /etc/thin/rails_app.yml -c /home/sandip/rails_app --servers 3 -e production
>> Wrote configuration to /etc/thin/rails_app.yml
thin configuration file will look like
Start/stop/restart Nginx & thin server using command
sudo service nginx start|stop|restart
sudo service thin start|stop|restart
Read More…
by sandipransing
Ruby On Rails Installation on fresh ubuntu machine
Installation steps are applicable to ubuntu versions interpid, karmic koala.
Make necessary changes according to package manager provided by other
linux operating systems in order install ruby and rails.
Before getting started to installations make sure to build essential packages
on fresh ubutnu machine. Ubuntu machine has built in apt-get package manager
and that i loves because it is very to use as compared to other OS.
sudo apt-get install build-essential
Now there are many versions of ruby available including latest 1.9.2
But would like to prefer ruby version 1.8.7 as it is the most stable version
as of now.
I would like to recommend installtion of Ruby Enterprise Edition (REE) version as it is uses minimal system resources and consumes less memory.
Instrunctions to setup normal ruby and rails environment
1. Install Ruby, Rails, MySQL, irb and neceesary packages using single command
sudo apt-get install ruby ri rdoc mysql-server libmysql-ruby ruby1.8-dev irb1.8 libdbd-mysql-perl libdbi-perl libmysql-ruby1.8 libmysqlclient15off libnet-daemon-perl libplrpc-perl libreadline-ruby1.8 libruby1.8 mysql-client-5.1 mysql-common mysql-server-5.1 rdoc1.8 ri1.8 ruby1.8 irb libopenssl-ruby libopenssl-ruby1.8 libhtml-template-perl mysql-server-core-5.1 libmysqlclient16 libreadline5 psmisc
2. Install ruby gems
wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz
tar xvzf rubygems-1.3.5.tgz
cd rubygems-1.3.5
sudo ruby setup.rb
3. Create symbolic links to installation paths
sudo ln -s /usr/bin/gem1.8 /usr/local/bin/gem
sudo ln -s /usr/bin/ruby1.8 /usr/local/bin/ruby
sudo ln -s /usr/bin/rdoc1.8 /usr/local/bin/rdoc
sudo ln -s /usr/bin/ri1.8 /usr/local/bin/ri
sudo ln -s /usr/bin/irb1.8 /usr/local/bin/irb
4. Setup gemrc in order to avoid rdoc installation and to setup gem sources.
Add following lines to ~/.gemrc file
---
gem: --no-ri --no-rdoc
:benchmark: false
:verbose: true
:backtrace: false
:update_sources: true
:sources:
- http://gems.rubyforge.org
- http://gems.github.com
:bulk_threshold: 1000
5. Install rails
sudo gem install rails --no-rdoc --no-ri
Ruby Enterprise Edition i.e. REE (ruby 1.8.7) Installation
This will install ruby, rails, mysql, nginx and passenger
1. Download REE setup and install it
wget http://rubyforge.org/frs/download.php/68719/ruby-enterprise-1.8.7-2010.01.tar.gz /opt/ruby
cd /opt
./ruby/installer
2. Add ruby inside path
vi ~/.bashrc
# Add following line at the end of file
export PATH=/opt/ruby/bin:$PATH
Thanks to @vwadhwani!
Read More…
by sandipransing
ImageMagick Installation
Ubuntu machine has default apt-get package manager.
To install imagemagick following packages needs to be installed.
apt-get install imagemagick librmagick-ruby libmagickwand-dev
RMagick gem install
gem install rmagick
If you still facing problems with gem installation, Please look that following packages are installed
on your system.
dpkg -l | grep libmagickcore-dev graphicsmagick-libmagick-dev-compat
If there are no packages installed then try to install then first.
apt-get install libmagickcore-dev graphicsmagick-libmagick-dev-compat
Try to install rmagick gem again. Now it should be installed without any error.
Read More…
by sandipransing
Check out this SlideShare Presentation: Termtter ruby gem is provides a way to work with twitter which is easy to use and integrate. Basically it can be used in ruby and rails application to get full control over twitter as like we have in web browser. Also, it works with terminal.
Read More…
by sandipransing
I believe this post should clear basic coding standards before getting started with rails development.
I just came with conversion started for declaring variables on rubyonrailstalk google group and that ended up with exploring the concepts of rails MVC coding principles. so, i thought it would be nice if they gets summarized somewhere.
The question raised was -
"How to declare variables like arrays so that they are available everytime that layout or its related
partials are used. Putting @myarray = MyArray.all into every action in every controller doesn't seem very dry, so I guess I'm just looking for a very simple straighforward convention, but can't seem to find it documented anywhere or figure it out" -- capsized
Before getting into actual conversion, I would like to notedown what rails is.
Rails is web framework developed in ruby language. The main purpose behind is to make programmers life easy and development would be a fun. It is built over MVC framework and philosophy includes DRY, Convention over configuration and REST.
Pasting debate conversion as it is.
Normally something like that goes into a high-level filter, like one
in ApplicationController. -- Xavier Noria
Put a before_filter in your ApplicationController.
class ApplicationController
before_filter :set_my_array
private
def set_my_array
@myarray = MyArray.all
end
end
-- Andy
If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view. -- Colin
And here goes the debate started. First of all, i was also agreed with this suggestion but next reply
started conversion.
It's dirty, horrible, bad form, breaks the separation of layers...
Don't call the model from the view! -- Andy
Beware of the MVC police Colin, this suggestion will certanly not get
good housekeeping seal of approval :D
I agree through. I'm not gonna add a before filter just to set
MyArray.all into a class variable. I'd rather call it directly and claim
to be pragmatic. --Sharagoz
But you are wrong. The view should never, ever, ever touch the database.
Claim all you like. The fact is that in MVC architecture, database
queries don't belong in the view. A before_filter is the proper place
for this. --Marnen
Is it considered ok to call model methods if they do not touch the db,
or are model methods forbidden also? -- Colin
I would say the view can call instance methods of the model (attributes - real and virtual) but no class methods. So: is OK, but:
is not. It's a bit of a contrived example, but there you go. Accessing the model through instance variables you've created is OK, going directly to the model bypassing the controller is not. --Andy
I think it is appropriate for the view to call methods on the objects passed in by the controller, provided that these methods do not change the model or touch the database.
Example:
# controller
def my_action
@person = Person.find(params[:id])
end
#my_action.html.erb
Good: -- Marnen
Here started conclusion on topic
Good example. I just want to throw in a couple more twists and see what
you think.
1. What about methods on models that change themselves in some way?
Suppose the last_viewed_at method returned a previously stored time,
then updated the model to store a new current time. Maybe a bad example,
but I hope you get my meaning.
2. What about aggregating class methods like count, sum or avg?
Obviously a class methods and does touch the database. I assume it would
be better to let the controller deal with stuff like this.
Controller
@person_count = Person.count
View -- Robert
I don't know what you mean by dirty, it saves several lines of code
and when looking at the view code it is easier to see what is
happening than to see a variable that has to be hunted for in a filter
somewhere to find out what it is.
It does not break the separation of layers any more than calling an
instance method of a model does when using something like > Don't call the model from the view!
@person.name is a model call from the view -- Colin
But think how many lines of code you are going to have to go edit when you realize that you need to change it.
Also, I wouldn't consider Person.all to be more clean than @people. What if you need to exclude some? Person.all :conditions => {whatever}, if you are just using a before filter, it is easy to override, you can override it for any given controller, and for any given controller method. If it's hard coded into the view, then that view has to serve everybody's wishes, it ends up having to know how it is to be used, and having lots of brittle conditional code for each of these situations.
This is why the controller must be responsible for supplying the appropriate data to the view, not the view being responsible for creating it's own data.
It might start as innocently as Person.all, it can easily turn into
if this
Person.all
elsif that
OtherPerson.all
else
Person.all + OtherPerson.all
end -- Josh
This took another turn in conversion -
Did you misunderstand my post? I was arguing for putting it in a filter rather than in the view (hence saying the 4 lines of before_filter, private, def and end was worth it).
It sounds like - when you start with "But" - that you disagree, but the rest of your post seems to be arguing from the same side as my posts. -- Andy
And finally Colin ended up conversion with conclusion -
An excellent post if I may say so that brings out the salient points I
think. Can the issues be summarised as follows?
- The controller should provide all the data that the view should display in instance variables (@person for example).
- The view is expected to understand the structure of the objects and so can access attributes (virtual or otherwise) of the objects.
- If the model needs to access the db in order to provide an attribute value, or accessing the attribute has some side effect that affects the db, then this is ok, providing the view does not 'know' that the side effect or db access is happening. (Not very well written but I hope you know what I mean).
- The view must not call any method of the model who's purpose is to perform an action rather than return a value.
- The view should not make any explicit use of model classes. For example there should be no reference to Person or any other model class -- Colin
Read More…
by sandipransing
WordPress is a open source software developed by and for community with ongoing development on it.
Easy installation, customizable, with lots of available plugins, themes and SEO friendly are the strengths of it!
Software is mainly serves the purpose of blogging, hosting static websites.
People with knowledge of php, javascipt and little knowledge of mysql db can customize it however they want.
Minimum server requirements
- PHP 4.3 or greater
- MySQL 4.1.2 or greater
- apache/ngnix ( or any web server supporting php & mysql )
For detailed information on installation click
Now you will need to decide where on your web site you'd like your blog to appear:
In the root directory of your web site. (For example, http://yoursite.com/)
In a subdirectory of your web site. (For example, http://yoursite.com/blog/
This can be done by adding new route at nginx configuration file or deploying wordpress
software inside blog directory of main website.
There are millions of satisfied users using word-press blog.
To create and start blogging with free wordpress.com blog click
WordPress MU multiblog software provides a way to create thousands of wordpress blogs
just like wordpress.com site does.
Download and detailed information on installation click
Read More…
by sandipransing
There are different ways to load particular file in rails application environment if the required file exists.
1. Using RAILS_ROOT
if File.exists?(file=File.join(RAILS_ROOT,'config', 'initializers', 'smtp_gmail.rb'))
require file
end
2. Using Rails.root & join
require Rails.root.join('config', 'initializers', 'smtp_gmail.rb')
3. Using Rails.root, join & exists? method.
require file if File.exists?(file = Rails.root.join('config', 'initializers','smtp_gmail.rb'))
4. Using File and direct path to file
require File.join('root','app','config', 'initializers', 'smtp_gmail.rb')
Among all above methods of loading file, Using Rails.root, join & exists? method seems to be pretty good to have.
Any improvements are most welcome!
Read More…
by sandipransing
The Tortoise svn client on windows is one of my favorite svn client.
I am working on ubuntu karmic koala from last one year.
There are kdesvn. smartsvn svn clients available on ubuntu but still
time haven't found any svn client as good as tortoise svn on windows.
Is there any alternative ??? Can tortoise svn client installation possible
using wine utility package in ubuntu ??
Read More…
by sandipransing
Change default favicon on blogger
Go to the layout click on Edit HTML link
Insert following link code inside head tag
<link href='IMAGE_ICON_LINK' rel='icon' type='image/x-icon'/>
Replace IMAGE_ICON_LINK url with your icon file url on web
Read More…
by sandipransing
RailsTinyMCE - A Rich Text Editor for ruby on rails
TinyMCE is a javascript rich text editor. It is easy to integrate with blogs, cms, messages and mailers.
Plugin uses jrails(jquery) and paperclip plugin for upload support.
Features
- Provides rich text editor
- Customisable TinyMCE plugins
- Easy to integrate
- Supports Image upload & insert
- Supports Media upload & Youtube embed
- TODO: Document upload plugin
1. Install rails_tiny_mce plugin using
./script/plugin install git://github.com/sandipransing/rails_tiny_mce.git
./script/generate rails_tiny_mce_migration
rake db:migrate
2. Install jrails(jquery) plugin using
./script/plugin install git://github.com/aaronchi/jrails.git
3. Install dependent plugins(if you didn't)
rake rails_tiny_mce:plugins
Above command will copy paperclip, responds_to_parent, will_paginate plugins to vendor/plugins directory.
- paperclip git://github.com/thoughtbot/paperclip.git
- responds_to_parent http://responds-to-parent.googlecode.com/svn/trunk
- will_paginate git://github.com/mislav/will_paginate.git
4. In your layout add following lines
<%= javascript_include_tag :defaults %>
<%= javascript_include_tiny_mce_if_used %>
<%= tiny_mce if using_tiny_mce? %>
5. Inside controller class on top add following lines
uses_tiny_mce(:options => AppConfig.default_mce_options, :only => [:new, :edit])
This AppConfig.default_mce_options is in config/initializers/tiny_mce_plus_config.rb, you could change the setting there
6. In your view add class mceEditor to text_area
Then append the following to the text area you want to transform into a TinyMCE editor.
:class => "mceEditor"
7. Install file lists
rake rails_tiny_mce:install
will Install following files:
app
|-- controller
|-- attachments_controller.rb
|-- helpers
|-- remote_link_renderer.rb
|-- models
|-- print.rb
|-- video.rb
|-- views
|-- attachments
|-- _show_attachment_list.html.erb
config
|-- initializers
|-- tiny_mce_plus_config.rb
public
|-- images
|-- tiny_mce
|-- javascripts
|-- tiny_mce
You may custom the config in tiny_mce_plus_config.rb.
Attention Note:
- Do not put <p> </p> around the textarea.
- If you are using old will_paginate plugin, change the url_for to url_option in remote_link_renderer.rb
Example use:
Create CRUD for post
./script/generate scaffold post title:string text:description
Run Migrations
rake db:migrate
Add following line to posts_controller.rb
uses_tiny_mce(:options => AppConfig.default_mce_options, :only => [:new, :edit])
Open /views/posts/new.html.erb and /views/posts/edit.html.erb
Modifiy following line
<%= f.text_area :description %> to <%= f.text_area :description, :class => "mceEditor" %>
Read More…
|