OAuth with OmniAuth and Twitter 6

Posted by arunagw on November 07, 2011

Hi Folks,

If you want to have OAuth in your Rails Application with twitter. OmniAuth is the best gem to use.

OmniAuth provides list of  Strategies to use many OAuth for your application. Here is the List of Strategies.

Showing here a Twitter Strategy for OmniAuth. Twitter uses the OAuth 1.0a flow, you can read about it here: https://dev.twitter.com/docs/auth/oauth

For using Twitter OAuth you have to register a Application on Twitter (https://dev.twitter.com/apps/new)

Once you done with the registration obtain the Consumer Key and Consumer Secret from the Twitter Application.

Be sure to put the callback URL in the application. Callback URL is the URL where user will land after successful authentication.

Showing an image here how to register an Application with Twitter.

 

Here showing some of the steps :

Generate a new Rails Application:

rails new TwitterAuth

Update your gemfile add omniauth-twitter gem into that

gem "omniauth-twitter"

Create a config/initializers/omniauth.rb file.
Paste your key instead of XXXX, and secret instead of YYYY

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, 'XXXX', 'YYYY'
end

All Done!

Just start the server

bundle exec rails server

And hit the URL

http://localhost:3000/auth/twitter

And you should be landing on the Twitter Authorize page!

After success your app will redirect to your given callback URL with information and token!

At OmniAuth.org you can try out different -2 Strategies.

 

Useful links :

Respond to Custom Formats in Rails 4

Posted by arunagw on October 24, 2011

We usually respond some of the known formats in Rails Application like HTML, XML, JavaScript, RSS and some custom.

Have you tried to use your own custom format for your Rails Application?

Yes you can use your custom format in Rails Application.

Here showing a simple Rails Application with responding custom formats.

Get a new app

rails new music_library 

Get a scaffold into App

rails generate scaffold mp3 title:string url:string description:text 

Ok so you are ready to serve some music on your app with some formats!

Now you have to register MIME types in the Rails Application.

For that open up Rails.root/config/initializers/mime_types.rb

Mime::Type.register 'audio/mpeg' , :mp3

Now you can serve .mp3 and content

For that your respond block should look like

def show
  @mp3 = Mp3.find(params[:id])
  respond_to do |format|
    format.mp3 { redirect_to @mp3.url }
  end
end

Now if you call this action with .mp3

http://localhost:3000/mp3s/1.mp3

You will redirect_to @mp3 url.

Happy adding custom formats!!

X-Request-Id tracking and TaggedLogging in Rails3.2

Posted by arunagw on October 21, 2011

Rails 3.2 will come with X-Request-Id tracking and TaggedLogging support!! Recently DHH added this feature here!

This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs.

If you have application on SAS model. Where you have logs filled with mixed request for all your customers. May be you need to filter out requests start with some specific subdomain. TaggedLogging will help you in that.

Where as the X-Request-Id feature will help you to track log with the same request. So in mixed logs you can easily find out the unique id logs for a request.

It will tag the log with the unique id for that request in the log. So later you can easily trace them down.

May be later on you can add more tags for your logs. If those methods are supported by the request object!

I am showing here some logs here with X-Request-Id

[2011-10-21 19:57:55] INFO  WEBrick 1.3.1
[2011-10-21 19:57:55] INFO  ruby 2.0.0 (2011-10-19) [x86_64-darwin11.2.0]
[2011-10-21 19:57:55] INFO  WEBrick::HTTPServer#start: pid=1585 port=3000
[9fda80066583f52e695a089d8622439c] 

Started GET "/blogs" for 127.0.0.1 at 2011-10-21 19:57:59 +0530
[9fda80066583f52e695a089d8622439c]  Processing by BlogsController#index as HTML
[9fda80066583f52e695a089d8622439c]    Blog Load (0.2ms)  SELECT "blogs".* FROM "blogs"
[9fda80066583f52e695a089d8622439c]    Rendered blogs/index.html.erb within layouts/application (8.8ms)
[9fda80066583f52e695a089d8622439c]  Completed 200 OK in 32ms (Views: 30.4ms | ActiveRecord: 0.3ms)
[2011-10-21 19:57:59] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
[0962521e4215d645367b58fa41da9f0d] 

Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2011-10-21 19:57:59 +0530
[0962521e4215d645367b58fa41da9f0d] Served asset /application.css - 304 Not Modified (0ms)
[2011-10-21 19:57:59] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
[a7204cec4d2b2e930ac05b41fa1a5c65] 

Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2011-10-21 19:57:59 +0530
[a7204cec4d2b2e930ac05b41fa1a5c65] Served asset /jquery_ujs.js - 304 Not Modified (1ms)
[2011-10-21 19:57:59] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
[202eadd97820dfbf429f87f4725324c3] 

Started GET "/assets/blogs.css?body=1" for 127.0.0.1 at 2011-10-21 19:57:59 +0530
[202eadd97820dfbf429f87f4725324c3] Served asset /blogs.css - 304 Not Modified (2ms)
[2011-10-21 19:57:59] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
[769a2752906bb0c2c5d1eae0a76ac328]

Here I showed some logs in strong. They are the same request for the index page tagged with the same unique id.
The same concept for the subdomain. The subdomain will also come as a tag.

You can also log some of the custom events in log file with the tags!

Logger.tagged("BCX") { Logger.info "Stuff" }                            # Logs "[BCX] Stuff"
Logger.tagged("BCX", "Jason") { Logger.info "Stuff" }                   # Logs "[BCX] [Jason] Stuff"
Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"

How to configure it ??

Open up your production.rb or your custom environment file, uncomment the line for log_tags

config.log_tags = [ :subdomain, :uuid ]

And you will get tagged logs with useful information.

Useful links :

Commit URL : https://github.com/rails/rails/commit/afde6fdd5ef3e6b0693a7e330777e85ef4cffddb
Feature Branch : 3.2

Cheers,
@arunagw

Rails 3.1 and JRuby

Posted by arunagw on October 10, 2011

Hi Folks,

If you are doing any application in which you required JRuby as a platform. You can use Rails3.1 with that. activerecord-jdbc-adapter 1.2.0 is ok with that!

All the steps are same as for the normal Rails Application

You can find more details here http://blog.jruby.org/2011/09/ar-jdbc-1-2-0-released/

 

Cheers,
Arun

Submit a patch for Rails on Github using “fork and edit button” 4

Posted by arunagw on September 11, 2011

Hi Folks,

I have recently written about my Rails Contributions experience here.

I see that now days contribution is Rails is increased. People love to contribute in Open Source projects. And the way should be easy not painful.

I found that some people are struggling in submitting Pull Requests in Rails on Github. So i thought of writing the same to help them.

Some people are new to git and they don’t know much about git… or sometime patch is very small and they want to use Github’s “fork and edit this file” feature to submit a patch.

And some people who are good in Rails will do it in more easy manner. And easy to open multiple pull request at a time from the same branch.

I am writing some steps to use Github’s fork and edit feature to open pull request.

Open up your project on Github open up file where you want to change

Change your desired things into the file. You can only change one file in one commit

Propese your file changes! Here you can write about your changes. Give some references about issue. Can see the file changed. Can see the commits which you have made.

Change commit is the most important part. The reason is when people are doing changes in specific branch. Let’s take a example of Rails. If you are going to submit a patch against Rails 3.0.X version then you must have to choose 3-0-stable branch instead of master in Base branch.

After updating the commit range you can submit the Pull Request and also must see the File Changed.

Use this feature when you are fixing any typos, updating any docs. For submitting any code changes you should be running tests. :-)  

Feel free to ask me if you face any problem in doing these things. We want more contributions!

You can tweet me @arunagw or catch me on my email any time.

Cheers!

Serialized Attributes Rails 3 1

Posted by arunagw on August 27, 2011

This post will guide you how to do Serialization for your attributes in Rails.

Serialize means you want to save arbitrary Ruby data structure into the database.

Let consider we have a User model in which we want to store preferences for user in a Ruby data structure format. Previously it was only YAML.

class User < ActiveRecord::Base
  serialize :preferences 
end
user = User.find 1
user.preferences = {:foo =>  'bar'}
user.save

So now we can pass a second parameter to serialize method to use that serialization method.

class User < ActiveRecord::Base
  serialize :preferences, SomeCoolEncoder.new
end

You need to implement this encoder! It can be a JSON, XML, Base64. Or what every encoding technique you like to use.

A sample encoder look like this.

class Base64Encoder
  def load(value)
    return unless value
    value.unpack('m').last
  end

  def dump(text)
    [text].pack('m')
  end
end

This new encoder must have these methods in it!

So now you attribute is serialized and you can store data in it in your given format.

Ok so now we talk about ActiveModel::Serialization

ActiveModel::Serialization will give you serialized attribute for your classes.

A very simple example to use ActiveModel::Serialization

class Post

  include ActiveModel::Serialization

  attr_accessor :title

  def attributes
    {'title' => title}
  end

end

# So you can use like 

post = Post.new
post.serializable_hash   # => {"title"=>nil}
post.name = "Rails is Cool!!"
post.serializable_hash   # => {"name"=>"Rails is Cool!!"}

Can use two inbuilt Serialization techniques

include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml

This is a very short intro for Serialization. Hope i will write more in detail soon!!

I got this from @tenderlove talk in RailsConf2011

Rails 3.0.10 and JRuby 1

Posted by arunagw on August 05, 2011

Finally, The Rails is coming with template support with JRuby platform. We used to use “-m” option to generate new Rails Application for JRuby platform. Which is no more need now.

Just set your platform to JRuby and create a new Rails Application as you do normally and it will generate a Application which is ready to go. No more tweaks required..!!

This pull request which get merged into Rails 3-0-stable branch and it’s shipped with Rails 3.0.10.rc1 and will come with Rails 3.0.10.

This feature is also coming with Rails 3.1.

Showing here some of the example which will create Rails Application for JRuby platform. I have tested this on JRuby 1.6.3 version.

rvm jruby-1.6.3
# Will set your environment for JRuby 1.6.3 version.

Time to create rails app. This will generate a rails app for JRuby platform. Things like database.yml, Gemfile will generated specifically for JRuby platform.

rails new myapp

database.yml

# SQLite version 3.x
#   gem 'activerecord-jdbcsqlite3-adapter'

development:
  adapter: sqlite3
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3

production:
  adapter: sqlite3
  database: db/production.sqlite3

Gemfile

source 'http://rubygems.org'

gem 'rails', '3.0.10.rc1'

gem 'jruby-openssl'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'activerecord-jdbcsqlite3-adapter'

# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
# gem 'ruby-debug19', :require => 'ruby-debug'

# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'

# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
#   gem 'webrat'
# end

You can see in Gemfile the changes. It requires gem 'jruby-openssl' gem and gem 'activerecord-jdbcsqlite3-adapter' gem. Which is required for JRuby platform.

Same work to generate for mysql and postgres.

rails new myapp -d mysql

And that’s all.!!

Your Application is ready to run. Just do bundle install and all set. wOOtt..!!

Post comments and discuss things if you guys still facing any issue. You can also post issue on Rails Issues and ask me to look into that.

Some Useful links related to post:

  1. Activerecord-jdbc-adapter
  2. Jruby.org
Cheers,

Rails3 application with Jruby 1

Posted by arunagw on March 28, 2011

If you are living on edge and you are using Rails3 then you need follow this. Rails3 With JRuby

 

Hi All,

Recently i have started a Rails3 application which will use Jruby.

I have gone through some of the steps for that application up and running.

If you are using RVM then it’s easy to install Jruby. In the latest RVM version Jruby-1.6.0 is the default one. So my recommendation is first update the RVM itself then install Jruby.

To update RVM and get the Jruby-1.6.0 installed

rvm update 
# But if you are already on the latest RVM then you will get message the "rvm update has been removed".

#To install Jruby

rvm install jruby

After installing Jruby you need to switch your environment to Jruby

 
rvm use jruby
#Using /Users/arunagw/.rvm/gems/jruby-1.6.0

Can check by using

~~>jruby -v                                                                                                                                                                          
jruby 1.6.0 (ruby 1.8.7 patchlevel 330) (2011-03-15 f3b6154) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_22) [darwin-x86_64-java]
~~>ruby -v                                                                                                                                                                           
jruby 1.6.0 (ruby 1.8.7 patchlevel 330) (2011-03-15 f3b6154) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_22) [darwin-x86_64-java]

Now you are ready to play with Jruby stuff.

You can do some basic stuff like irb to test things

irb
#IRB will also work
jirb
# JIRB will also work

Time to install Rails in Jruby environment

gem install rails 

#Will also work

jruby -S gem install rails

All set. Create your Rails application.

rails new my_app

Above command will create a rails application but not useful for Jruby platform.

For all setting just run

rails new my_app -m http://jruby.org/rails3.rb

This will do all setup for you for a rails3 app in Jruby.

You may need to change/update your Gemfile for your gems.

Problems i faced.

rake db:create will give you an error if you are using Mysql with Jruby.

uninitialized constant Mysql::Error

Here is the ticket information about this.

Solution for this problem right now is to create database manually.

After that all will work. No more hurdles i found.

If you got in any problem let me know. We will try to solve that together.

Links may be useful to find stuff

1. Jruby Activerecord adaptor.
2. My Sample Application
3. RVM

—–

Arun

Use selenium as a script

Posted by arunagw on March 22, 2011

Hey All,

I came with a situation where i need to test things from browser. It nothing to do with the different browsers. It just to check some validations, some messages with some existing data with me.

I can’t touch the code base. It’s something like QA work.

I am not very much aware about using of selenium IDE which is available in browsers.

I look into the selenium world with ruby and found some interesting stuff that i can script my test and run for a browser.

To run into the browser i need to setup selenium-rc server running.

I have done it in my way. Just small code and using selenium-client gem which allows me to start and stop the selenium-rc server.

Here is my code for selenium-rc server. It also includes the selenium-jar file.
https://github.com/arunagw/selenium-server

For running selenium-rc server. Just clone it. bundle install and then rake selenium:rc:start

All set. Now you are ready to run selenium script from your local machine.

To test things i am using hitting up google.com and validating stuff. A google example is also given on the selenium-client gems readme.

#!/usr/bin/env ruby
#
# Sample Ruby script using the Selenium client API
#
require "rubygems"
gem "selenium-client", ">=1.2.16"
require "selenium/client"

begin
  @browser = Selenium::Client::Driver.new \
      :host => "localhost", 
      :port => 4444, 
      :browser => "*firefox", 
      :url => "http://www.google.com", 
      :timeout_in_second => 60

  @browser.start_new_browser_session
    @browser.open "/"
    @browser.type "q", "Selenium seleniumhq.org"
    @browser.click "btnG", :wait_for => :page
    puts @browser.text?("seleniumhq.org")
ensure
  @browser.close_current_browser_session    
end

You can just run above script after start the selenium-rc server and see the result yourself in the browser.

Some useful links for get up and running selenium with ruby.

Selenium-client for ruby :- https://github.com/ph7/selenium-client
All about selenium with ruby :- http://seleniumhq.org/projects/ruby/

Gem 1.5 with Rails 2.3 5

Posted by arunagw on March 19, 2011

You may fall down into the situation where you don’t have RVM and your system gem is upgraded for using latest things.

And your old application is still running on older version of rails.

This is just a workaround of using Gem > 1.3.7 in Rails 2.3 Applications.

I have tested this solution with Rails 2.3.5 and different version of gems.

After upgrading gems to 1.6.2 i have got an error

/activesupport-2.3.5/lib/active_support/dependencies.rb:55: 
uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

To fix this error need to update boot.rb file. Place this at the top of boot.rb

require 'thread'

After adding this you should be getting this error

 
/gem_dependency.rb:119:in
 `requirement': undefined local variable or method `version_requirements'

To fix this error you need update your environment.rb file.
Add this code above your Rails::Initializer.run block.

if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.3.7')
 module Rails
   class GemDependency
     def requirement
       r = super
       (r == Gem::Requirement.default) ? nil : r
     end
   end
 end
end

Now your application should start running properly. Have fun ;)

Now you can downgrade or upgrade your system gem version. Your application will still run.

Above workaround works for me very well. Any other ideas?


Follow

Get every new post delivered to your Inbox

Join other followers