My new gem – label_better_rails

Hi after a success of my previous gem sticky-rails ( gemmified version of sticky jquery plug-in)  , I have created another gem and this also a gemmified version of another beautiful jquery plug-in label_better ,
This will help you to add label_better gem to your rails application assets pipeline quickly , Home page for this gem is https://github.com/navinspm/label_better_rails

Thanks to http://www.thepetedesign.com/demos/label_better_demo.html

Label your form input like a boss with beautiful animation and without taking up space

Screen shot

Installation

Add this line to your application’s Gemfile:

gem 'label_better_rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install label_better_rails

label_better is a jquery_plug in that gives beautiful animation to your label , so please check if you are using the jquery on your rails app, and add jquery.label_better in your application.js

Your app/assets/javascripts/application.js appear like:

//= require jquery
//= require jquery_ujs
//= require jquery.label_better
//= require_tree .

Then in your view file where you want to add label_better just remove our default rails label then give a class name and the placeholder to the field example

    <%= f.text_field :firstname ,:class => 'label_better', :placeholder => 'firstname'%><br/><br/>
    <%= f.text_field :lastname ,:class => 'label_better', :placeholder => 'lastname'%><br/><br/>
    <%= f.email_field :email,:class => 'label_better', :placeholder => 'email' %><br/><br/>
    <%= f.phone_field :phonenumber,:class => 'label_better', :placeholder => 'Mobile' %><br/><br/>
    <%= f.url_field :website ,:class => 'label_better', :placeholder => 'Website'%><br/><br/>
    <%= f.password_field :password ,:class => 'label_better', :placeholder => 'confirmpassword'%><br/><br/>
    <%= f.password_field :confirmpassword , :class => 'label_better', :placeholder => 'confirmpassword' %>

then add javascript in your view file

$("input.label_better").label_better({
    position: "top", 
    animationTime: 500, 
    easing: "ease-in-out",
    offset: 5, 
    hidePlaceholderOnFocus: true 
  });

Change this values depends on your need

Contributing

  1. Fork it ( https://github.com/[my-github-username]/label_better_rails/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request
Advertisements

Collection Of Database Queries in Rails

Retrieving a Single Object

client = Client.find(10)

client = Client.take

client = Client.first

client = Client.last

Client.find_by first_name: ‘Lifo’

Client.where(first_name: ‘Lifo’).take

Client.find_by! first_name: ‘Lifo’

Retrieving Multiple Objects

client = Client.find([1, 10])

Client.take(2)

Client.first(2)

Client.last(2)

Retrieving Multiple Objects in Batches

User.all.each do |user|

 NewsLetter.weekly_deliver(user)

end

Conditions

Pure String Conditions

Client.where(“orders_count = ‘2’”)

Client.where(“orders_count = ?”, params[:orders])

Client.where(“orders_count = ?”, params[:orders])

Client.where(“orders_count = #{params[:orders]}”)

Client.where(orders_count: [1,3,5])

Post.where.not(author: author)

Ordering

Client.order(:created_at)

# OR

Client.order(“created_at”)

Selecting Specific Fields

Client.select(:name).distinct

Limit and Offset

Client.limit(5)

Client.limit(5).offset(30)

Group

Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).group(“date(created_at)”)

Having

Order.select(“date(created_at) as ordered_date, sum(price) as total_price”).

 group(“date(created_at)”).having(“sum(price) > ?”, 100)

Overriding Conditions

Post.where(‘id > 10’).limit(20).order(‘id asc’).except(:order)

Post.where(‘id > 10’).limit(20).order(‘id desc’).only(:order, :where)

Client.where(“orders_count > 10”).order(:name).reverse_order

Null Relation

Post.none

Readonly Objects

client = Client.readonly.first

client.visits += 1

client.save

Optimistic Locking

c1 = Client.find(1)

c2 = Client.find(1)

c1.first_name = “Michael”

c1.save

c2.name = “should fail”

c2.save # Raises an ActiveRecord::StaleObjectError

Find or Build a New Object

find_or_create_by

Client.find_or_create_by(first_name: ‘Andy’)

find_or_initialize_by

The find_or_initialize_by method will work just like find_or_create_by but it will call new instead of create. This means that a new model instance will be created in memory but won’t be saved to the database. Continuing with the find_or_create_by example, we now want the client named ‘Nick’:

Finding by SQL

Client.find_by_sql(“SELECT * FROM clients

 INNER JOIN orders ON clients.id = orders.client_id

 ORDER BY clients.created_at desc”)

Existence of Objects

Client.exists?(1)

Calculations

Client.coun

Client.where(first_name: ‘Ryan’).count

Client.includes(“orders”).where(first_name: ‘Ryan’, orders: { status: ‘received’ }).count

Client.average(“orders_count”)

Client.minimum(“age”)

Client.maximum(“age”)

Client.sum(“orders_count”)

Form Helpers

<%= form_tag do %>

A Generic Search Form

<%= form_tag(“/search”, method: “get”) do %>

 <%= label_tag(:q, “Search for:”) %>

 <%= text_field_tag(:q) %>

 <%= submit_tag(“Search”) %>

<% end %>

Checkboxes

<%= check_box_tag(:pet_dog) %>

<%= label_tag(:pet_dog, “I own a dog”) %>

<%= check_box_tag(:pet_cat) %>

<%= label_tag(:pet_cat, “I own a cat”) %>

Radio Buttons

<%= radio_button_tag(:age, “child”) %>

<%= label_tag(:age_child, “I am younger than 21”) %>

<%= radio_button_tag(:age, “adult”) %>

<%= label_tag(:age_adult, “I’m over 21”) %>

Helpers

<%= text_area_tag(:message, “Hi, nice site”, size: “24×6”) %>

<%= password_field_tag(:password) %>

<%= hidden_field_tag(:parent_id, “5”) %>

<%= search_field(:user, :name) %>

<%= telephone_field(:user, :phone) %>

<%= date_field(:user, :born_on) %>

<%= datetime_field(:user, :meeting_time) %>

<%= datetime_local_field(:user, :graduation_day) %>

<%= month_field(:user, :birthday_month) %>

<%= week_field(:user, :birthday_week) %>

<%= url_field(:user, :homepage) %>

<%= email_field(:user, :address) %>

<%= color_field(:user, :favorite_color) %>

<%= time_field(:task, :started_at) %>

<%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %>

<%= range_field(:product, :discount, in: 1..100) %>

The Select and Option Tags

<%= select_tag(:city_id, ‘<option value=”1″>Lisbon</option>…’) %>

TIme zone

<%= time_zone_select(:person, :time_zone) %>

Country select

https://github.com/stefanpenner/country_select

Using Date and Time Form

<%= select_date Date.today, prefix: :start_date %>

<%= select_year(2009) %>

<%= select_year(Time.now) %>

Uploading Files

<%= f.file_field :picture %>

layout helpers

<%= javascript_include_tag “main”, “columns” %>

<%= stylesheet_link_tag “http://example.com/main.css” %>

<%= image_tag “header.png” %>

<%= video_tag “movie.ogg” %>

<%= audio_tag “music.mp3” %>

Audio Streaming in Ubuntu using Shoutcast and Internet DJ Control

     If you ever want to stream your rails application audio file using shoutcast I will show you how to do this

firt install and configure shoutcast
cd /tmp
wget http://download.nullsoft.com/shoutcast/tools/sc_serv_1.9.8_Linux.tar.gz

If you get error while trying to execute this command then you don’t have wget command installed to your system. For Debian and Ubunutu use the following command to install it:

Code:
apt-get install wget

Again If you get the error then go to the shoutcast site then download the package

 Next we need to create the folder for our shoutcast server and extract the archive

Code:
mkdir /home/shoutcast
tar -zxf sc_serv_1.9.8_Linux.tar.gz -C ./home/shoutcast

Navigate to the shoutcast folder and clear the config file because it has comments and configuration codes it may confuse you if you see them first time any way its better to clear the file

Code:
cd /home/shoutcast
echo > sc_serv.conf

5. Open the file sc_serv.conf

Code:
nano sc_serv.conf

Paste the following text

Code:
 MaxUser=32
 Password=changeme
 PortBase=8000
LogFile=sc_serv.log
RealTime=1
ScreenLog=1
ShowLastSongs=10
SrcIP=ANY
DestIP=ANY
Yport=80
NameLookups=0
 AdminPassword=adminpass
AutoDumpUsers=0
AutoDumpSourceTime=30
PublicServer=default
AllowRelay=Yes
AllowPublicRelay=Yes
MetaInterval=32768

You should modify these settings:

A. Change the MaxUsers , It can be many users but set minimum as possible
B. Set the Password to a value that you know because you need it to connect to the server in order to stream music to it.
C. Optionally you can change the port by changing the PortBase to some different port.
D. AdminPassword is the web interface password. Web interface is used for banning and kicking users from the server.

6. Start the server

Code:
screen
./sc_serv

Thats all next is to go for broadcaster software in windows and mac SAM broadcaster is a excellent software we have but If you  want to use ubuntu then InternetDJcontrol shortely called as IDJC

IDJC

first we need to install idjc

Code:

sudo apt-get install jackd qjackctl

then

Open Limits.conf

sudo gedit /etc/security/limits.conf

Add the following lines into the file :

@audio - rtprio 99
@audio - memlock unlimited
@audio - nice -19

then run idjc you can find it by searching IDJC in ubuntu search bar This is GUI of IDJC

 main

Go to view-> output you will see the window like this there go to configuration -> connection -> new and fill the details as shown then click OK

host

then in configuration -> format fill the details as follows

configuration image

configuration setting

If all set to correct then above localhost:8000 (8000 may change depends on port you set)  will appear as shown if not check the settings againlocalhost then click the localhost:8000 button if everything goes well the button has need to be stayed as pressed like this  then the green light will glow

connectedand that’s all you may listen your radio on shoutcast.com by searching your radio name which you given at the first time you starts the IDJC , if the green indicator doesnot glow check the shoutcast server running and see the serv.conf file port setting

If you want to use it in your rails application the jplayer fetch the stream and play it well check it on their website jplayer stream player

 

Thank you for reading me…………………

 

A simple instruction to Rspec – 3 in Ruby on Rails -4

This is small introduction about rspec version 3 for ruby on rails developers, and also note that this is not mean for techy geeks 🙂

Initial Setup
add gem 'rspec-rails', '~> 3.0.0'

then bundle install

And run rails generator rspec:install

Herein after spec files are automatically created when ever you create model, controller, view files, if you dont want any spec file to be created automatically then
in your application.rb

config.generators do |g|
g.test_framework :rspec,
view_specs: false,
helper_specs: false,
routing_specs: false,
controller_specs: true,
request_specs: false
end

put false wherever you dont want to create spec files
RSpec generators can also be run independently. For instance,

rails generate rspec:model post

All specs are created inside spec folder and to run test just type rspec in terminal

If you want to test only a particular file say products.rb in model then

 rspec ../rails_app/spec/models/products.rb

Thats all

Model specs

Examples
require "rails_helper"

describe Post do
it “checks it saves the data” do
expect(Post.count).to eq 0
@post=Post.create
@post.save
expect(Post.count).to eq 1
end
end

controller spec

require 'rails_helper'

RSpec.describe WelcomeController, :type => :controller do
it ‘has 300 status code’ do
get :index
expect(response.status).to eq(200)
end
end

Matchers

rspec-rails offers a number of custom matchers, most of which are
rspec-compatible wrappers for Rails’ assertions.

redirects
expect(response).to redirect_to(path)
templates
expect(response).to render_template(template_name)
assigned objects
expect(assigns(:widget)).to be_a_new(Widget)

Easy way to deploy Rails 4 application in Unicorn with Nginx

In this post I will show you how to host our rails application with unicorn and nginx

The first step is obviously to install nginx for that go to your control terminal then type

sudo apt-get install “nginx”

After the installation go to /etc/nginx/sites_enabled/ – (or wherever you installed nginx)

in this sites_enabled folder you have default.conf file delete that file and create new file called nginx.conf

server
{
listen 80 default;
#server_name example.com;
root /home/ideology/test_server_nginx/public;
try_files $uri/index.html $uri @unicorn;
location @unicorn {
proxy_pass http://localhost:3000;
}

error_page 500 501 502 503 /404.html;
}

save the file with above code

Now In your rails application folder gemfile.rb add gem “unicorn” and run bundle install

Then start your rails application with unicorn with port 3000

    /application_folder/unicorn -p 3000

Then you can seen your application in browser with nginx server at port 80

Thats all! very simple yes?……

To change environment to production

RAILS_ENV=production rake db:migrate

and then in your boot.rb file add this lines

require ‘securerandom’
ENV[‘SECRET_KEY_BASE’] = SecureRandom.hex

then start your rails application unicorn server

RAILS_ENV=production unicorn -p 3000

And thats all your environment is changed to production now ,

But this is just a fast start up only this is not the correct solution to host your application you need additionally unicorn configuration files for further reference http://unicorn.bogomips.org/

Gemmified version of jquery plug-in stick

Sticky is a jQuery plugin that gives you the ability to make any element on your page always stay visible .This is gemmified version of sticky

jQuery sticky 1.0.0 – http://stickyjs.com/

Installation

Add this line to your application’s Gemfile:

gem 'sticky-rails'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install sticky-rails

Usage

Sticky is a jQuery plugin that gives you the ability to make any element on your page always stay visible. , so please check if you are using the jquery on your rails app

//= require jquery

Your app/assets/javascripts/application.js must appear like:

//= require jquery
//= require jquery_ujs
//= require jquery.sticky.js
//= require_tree .

Basic Structure example from http://stickyjs.com/

<script>
  $(document).ready(function(){
    $("#sticker").sticky({topSpacing:0});
  });
</script> 

REMEMBER TO INITIALIZE IT!

If you are going to use coffee script:

$(document).ready ->
  $("sticker").sticky()

Or just javascript:

 $(document).ready(function(){
    $("#sticker").sticky({topSpacing:0});
  });

For more documentation please checkout the sticky-rails 4 repository here: https://github.com/garand/sticky

Gem Author

http://twitter.com/navinspm