Flowdock

Recent notes

RSS feed
December 2, 2016
0 thanks

Code Refactoring Gem – Flay

Flay examines code for structural likenesses. Differences in literal values, variable, class, method names, whitespace, programming style, braces vs do/end, props versus do/end, and so forth are all overlooked,making this absolutely rad. It’s fit for recognizing both correct and close matches, and does in certainty discover a few spots in Active Record where patterns repeat. In its current state, Flay’s output is very primitive: a list of repeated code nodes, together with a weight to rank them by and line numbers and file names where the repeated code appears. Code that flay reports as comparative is a decent possibility tool for refactoring.

Command to install

sudo gem install flay

Command to see output

CdPath to your project folder”

flaypath of the folder”

Eg : flay ./app/controllers - Identifies the code duplication in all the controllers.

flay ./app - Identifies the code duplication in entire project

flay ./app/controllers/example_controler.rb - Identifies the code duplication in specified controller.

Example of Output An output is generated of the code duplicated areas like this:

sridevi@carmatec-MS-7788$ flay ./app/models/*.rb
Total score (lower is better) = 1666

1) Similar code found in :call (mass = 170)
./app/models/example.rb:8
./app/models/example.rb:9
./app/models/example.rb:10
./app/models/example.rb:11
./app/models/example.rb:15
./app/models/example.rb:17
./app/models/example.rb:19
./app/models/example.rb:20
./app/models/example.rb:22
./app/models/example.rb:23

2) Similar code found in :defs (mass = 154)
./app/models/example.rb:260
./app/models/result.rb:195

3) Similar code found in :defs (mass = 138)
./app/models/feedback.rb:62
./app/models/example.rb:54
./app/models/result.rb:51

4) Similar code found in :call (mass = 136)
./app/models/example.rb:12
./app/models/example.rb:13
./app/models/example.rb:14
./app/models/example.rb:16
./app/models/example.rb:18
./app/models/example.rb:21
./app/models/example.rb:24
./app/models/example.rb:25

5) IDENTICAL code found in :defn (mass*2 = 128)
./app/models/result.rb:7
./app/models/summary_report.rb:7

6) IDENTICAL code found in :defn (mass*2 = 120)
./app/models/example.rb:17
./app/models/example.rb:23

The total app score of 1666 (‘lower is better’ advice holds true) can be viewed in its individual components showing areas that provide the most bang for the buck. For experienced developers operating on their own or in a small team Flay may be unnecessary. However, on larger projects (as the one I ran it on) or those with beginner or intermediate programmers it can help increase the maintainability of your codebase. http://www.railscarma.com/blog/technical-articles/code-refactoring-gem-flay/

December 1, 2016
0 thanks
November 28, 2016
0 thanks

Track Changes To Your Model’s Data with Paper Trail Gem

Paper trail lets us track all the changes in the models data for the purpose of its editing and versioning. By using this gem, we can see how a model looks, at every stage of its life-cycle and we can take it back to any version of the model data and we can even undo all the changes after a record has been destroyed so as to restore it completely.

gempaper_trail’ run bundle install to install it

After bundle install you can run the following command for adding versions table to your database

bundle exec rails generate paper_trail:install

bundle exec rake db:migrate

Add has_paper_trail method to your models for tracking.

class Product < ActiveRecord::Base
 	has_paper_trail

end

If you are using a current_user method then you can track who is responsible for particular change by the below callback

class ApplicationController

before_action :set_paper_trail_whodunnit end

Features of paper trail gem

It stores each and every change happened in the model  like create, update and destroy
It does not store any updates unless if any modifications
It allows you to get every version including the actual and even once destroyed

Basic Usage

Now you have a versions method which returns all the changes in particular model

product = Product.find 2

product.versions

# [<PaperTrail::Version>, <PaperTrail::Version>, ...]

Based on the vesrion you can find the changes that happened in a model

v = product.versions.last

   v.event # it returns update / create / destroy
   v.whodunnit #it returns a user id who did this
   v.reify the poduct as it was before the update

you can navigate versions by using previous_version and next_version methods

product = product.previous_version

   product = product.next_version #it returns nil if there is no object

   product.versions.last.whodunnit #it returns the user who did the particular change

For More Read From Here : http://www.railscarma.com/blog/technical-articles/track-changes-models-data-paper-trail-gem/

November 16, 2016
0 thanks

Ruby Developers

How to create a Ruby Gem Ruby Gems or “gem” is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries. It is easy to manage and install to your system and it can be used by various rails applications development.

Every RoR developer might have customised a gem at least once in his career, but not each one of them has actually, created a gem. Here, I am going to give a basic idea about how to create a new gem and how to publish it.

Kick off Before starting please make sure that you are using the latest ruby version. RVM is really useful in this case;

How to name your Gem Don’t blindly give a random name to your gem. Please take care of the following; Every dash represents a structure (folder, module) immersion Every underscore represents a joining in the class name

Some examples:

gem new_test_gem

  requirenew_test_gem’
  module/class NewTestGem

And:

gem gem-structure-new_test_gem

  requiregem/structure/new_test_gem
  module/class Gem::Structure::NewTestGem

How to create your Gem To create a gem; $ bundle gem new_test_gem It will create some basic files and directories.

Where to add your code or job Your beautiful code goes here

# lib/new_test_gem.rb

Once you have added your code into the lib file then you will have to update the gemspec file;

# new_test_gem.gemspec

For Complete details go through this link => http://www.railscarma.com/blog/technical-articles/how-to-create-a-ruby-gem/

November 11, 2016
0 thanks

Examples corrected

I have documented this method clearly with corrections to the examples shown in this page on my blog: http://www.rubyplus.net/2016/11/aliasmethod-in-ruby.html

November 8, 2016
0 thanks

Ways of Handling PayPal Refunds in Rails

PayPal Checkout includes payment solutions ranging from simple to robust that let the merchants as well as developers choose an integration option that can be the best-suited for their website and customers. In order to integrate Paypal Payment Gateway, we need to do the following:

  1. Have a PayPal business or Premier account.

  2. Create a PayPal app and get an access token. When we create a PayPal app, PayPal generates a set of OAuth client_id and secret keys for the application. PayPal generates these keys for both the PayPal sandbox and Live environments. To get an access token, pass the client-id:secret credentials in the Authorization header. We use the access token for authentication when we make REST API requests.

  3. To perform an end-to-end test of our Express Checkout with In-Context integration, create both merchant and buyer accounts in the PayPal sandbox environment.

www.sandbox.paypal.com/in/webapps/mpp/home Merchant : Select the Business account type and enter an email address and password. Buyer : Select the Personal account type and enter a high PayPal balance, such as 5000.

Once we create Paypal sandbox account then click on the “Profile” link for that account, look under the tab “API Credentials”. We will have the following information;

Paypal API Username
Paypal API Signature
Paypal API Password

Note: When we are ready to go live we would just use the credentials from our real paypal account instead of the ones from our sandbox account. The credentials can be found in the “My Profile” area under the left hand tab “My Selling Tools” under the option “API access”

How to handle Paypal refunds in Rails:

Method 1:

Paypal Rest API;

For more complex merchant sites, direct calls to PayPal APIs for an Express Checkout integration may be a more appropriate integration. REST APIs — We can develop an Express Checkout integration using PayPal REST APIs.

To integrate the Express Checkout with In-Context flow; developer.paypal.com/docs/api/ OR PayPal REST API Ruby SDK (paypal-sdk-rest gem): The PayPal REST SDK provides Ruby APIs to create, process and manage payment.

Installation: Add the gem our application, in Gemfile:

gem 'paypal-sdk-rest'

And then execute:

$ bundle install

Configuration:

rails g paypal:sdk:install

Refunds a transaction: Any transaction we can issue a refund (Both direct and captured payments):

Refund a completed direct payment (sale)
Refund an authorized and captured payment (capture)

Refund a completed payment (sale): If we must refund a completed payment, or sale, provide the sale id given to us in response to a completed payment along with an empty JSON payload for a full refund and for partial refunds, we can instead include an amount object in the JSON payload.

curl -v https://api.sandbox.paypal.com/v1/payments /sale/CARMAXYZC6136044L/refund \
-H "Content-Type:application/json" \
-H "Authorization: Bearer Access-Token" \
-d '{}'

Note: We should substitute all call-specific parameters, such as tokens and IDs, with our own. Response state of the refund:

pending- The refund is pending.
completed- The refund has successfully completed.
failed- The refund failed.

Refund a captured payment; We can also refund a captured payment: API:

https://api.paypal.com/v1/payments/capture/{capture_id}/refund

Note: We must provide an amount object for both full and partial refunds.

curl -v https://api.sandbox.paypal.com/v1/payments/capture/CARMAXYZC6136044L/refund \
-H "Content-Type:application/json" \
-H "Authorization: Bearer Access-Token" \
-d '{
"amount":
{
"currency": "USD",
"total": "50.54"
},
"description": "This is the capture refund description."
}'

Reference: https://developer.paypal.com

Method 2:

Paypal refund by using Active Merchant Gem:

ActiveMerchant Integration: http://railscasts.com/episodes/145-integrating-active-merchant

In our Application;

config/environment/development.rb

config.after_initialize do

ActiveMerchant::Billing::Base.mode = :test
::GATEWAY = ActiveMerchant::Billing::PaypalGateway.new(
:login => "seller_1229899173_biz_api1.xyz.com",
:password => "FXWU58S7KXFC6HBE",
:signature =>AGjv6SW.mTiKxtkm6L9DcSUCUgePAUDQ3L- kTdszkPG8mRfjaRZDYtSu"

)

end

Refunds a transaction: Take a look into paypal_common_api.rb file in Active Merchant Gem;

https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/gateways/paypal/paypal_common_api.rb
  1. For a full refund pass nil for the amount:

gateway.refund nil, 'CARMAXYZC6136044L'

This will automatically make the :refund_type be “Full”.

  1. For a partial refund just pass the amount as usual:

gateway.refund 100, 'CARMAXYZC6136044L'
def refund(money, identification, options = {})
commit 'RefundTransaction', build_refund_request(money,  identification, options)
end

Ex:

Gateway.refund(nil,'CARMAXYZC6136044L') => Full Refund.

Gateway.refund(798,'CARMAXYZC6136044L') => Partial Refund.

Reference: http://www.rubydoc.info/github/Shopify/active_merchant/ActiveMerchant/Billing/PaypalCommonAPI

Method3: Read More From Here==> http://www.railscarma.com/blog/technical-articles/ways-handling-paypal-refunds-rails/

October 27, 2016 - (<= v3.2.13)
1 thank

An example, with expiration time set

e.g.:

Rails.cache.fetch("out_of_stock_products", :expires_in => 5.minutes) do
  Product.all.joins(:inventory).conditions.where("inventory.quantity = 0")
end
October 17, 2016
0 thanks

How to generate & add sitemap to your Rails Application

Generate Sitemap: Required Gem: Sitemap generator:- github.com/kjvarga/sitemap_generator

SitemapGenerator is the easiest way to generate Sitemaps in Ruby. Rails integration provides access to the Rails route helpers within our sitemap config file and automatically makes the rake tasks available to us. Or if we prefer to use another framework, we can! We can use the rake tasks provided or run our sitemap configs as plain ruby scripts.

Sitemaps XML format:

The Sitemap protocol format consists of XML tags. All data values in a Sitemap must be entity-escaped. The file itself must be UTF-8 encoded.

The Sitemap must: Begin with an opening <urlset> tag and end with a closing </urlset> tag. Specify the namespace (protocol standard) within the <urlset> tag. Include a <url> entry for each URL, as a parent XML tag. Include a <loc> child entry for each <url> parent tag.

All other tags are optional. Also, all URLs in a Sitemap must be from a single host, such as www.xyz.com or estore.xyz.com. For more details: http://www.sitemaps.org/protocol.html

How to add a sitemap to a Rails app:

1, View for your sitemap:

# app/views/mysitemap/index.xml.erb

2, At your Controller: Let it be our object in view is @articles variable. It needs to get that from a mysitemap controller:

# app/controllers /mysitemap_controller.rb
MysitemapController <  ApplicationController
 layout nil
  def index
 headers['Content-Type'] =  'application/xml'
respond_to do |format|
 format.xml {@articles =  Article.all}
 end
 end
 end			

3, Add a route:

# config/routes.rb
get 'sitemap.xml', :to =>  'sitemap#index', :defaults =>  {:format  => 'xml'}

How to convert XML file to HTML: Read From Here http://goo.gl/Vp3chb

October 3, 2016
0 thanks

How To Generate a Swagger Docs For Rails API

Making API for a Rails application is simple for a Ruby on Rails developer. In any case, how different clients/customers will know whether the API is working fine or not without a customer side application. Is there any answer for this which I can report for API inside the Rails application, The answer is yes we have numerous instruments and methodologies however I would favor swagger UI.

In this article I am going to disclose how to make Rails API documentation using swagger UI.

Prerequisites:- I am going to use one sample posts application which serves API calls.

Gem:- To Integrate swagger UI for Rails API I am using a gem called swagger-docs. Add this gem to your Gemfile in your application and do bundle install.

Swagger initializer file:- After bundling the gem create an initializer in config/initializers(e.g. swagger.rb) and specify the following options:

#File config/initializers/swagger.rb

Swagger::Docs::Config.register_apis({

"1.0" => {

# the extension used for the API

:api_extension_type => :json,

# the output location where your .json files are written  to

:api_file_path => "public/apidocs",

# the URL base path to your API

:base_path => "http://localhost:3000",

# if you want to delete all .json files at each generation

:clean_directory => true,

# add custom attributes to api-docs

:attributes => {

:info => {

"title" => "Your application title",

"description" => "Rails API documention with Swagger UI.",

"termsOfServiceUrl" => "",

"contact" => ""

}

}

}

})

Refer below url for the list of configarations

https://github.com/richhollis/swagger-docs#configuration-options

swagger_controller and swagger_API are helpers to provide swagger UI documentation.

module Api

module V1

class PostsController < ApplicationController

respond_to :json

swagger_controller :posts, 'Post Controller'

swagger_api :create do

summary 'Creating posts'

notes 'Should be used for creating posts'

param :form, 'post[name]', :string, :required, 'name'

param :form, 'post[publish]', :boolean, :required, 'publish'

end

swagger_api :index do

summary 'Get all the posts'

notes 'Should be used for fetching all posts'

param :header, :Authoraization, :string, :required, 'Authoraization'

response :unauthorized

response :ok, "Success"

end

swagger_api :show do

summary 'Get all the posts'

notes 'Should be used for fetching a post'

param :path, :id, :string, :id

response :unauthorized

response :ok, "Success"

end

swagger_api :destroy do

summary 'Destroy the post'

notes 'Should be used for destroying a post'

param :path, :id, :string, :id

response :unauthorized

response :ok, "Success"

end

end

end

end

Read More From Here http://goo.gl/dMVHon

September 23, 2016 - (v3.2.3 - v4.0.2)
0 thanks

Usage of SQL and NoSQL Databases in single rails application(MySQL, PostgreSQL and MongoDB)

There are distinctive reasons why you should think about having various databases in your Ruby on Rails application. In my situation, I expected to store large quantities of data.

Consider default database is MySQL. In our application database.yml file write connections for MySQL in normal way. After that, for connecting postgresql in the same application we need to create custom files.

Create the custom database files to connect postgresql

We’re going to set up a second database called “Stats”

First of all, create the file config/database_stats.yml and populate it as you do with the primary database’s config file.

Your file will look something like this:

development:
adapter: postgresql
encoding: utf8
reconnect: false
database: db_info_development
pool: 5
host: localhost
username: postgres
password:

We’re now going to create a directory that will hold the schema and all the migrations of the Stats database.

Create directory with name db_stats in the rails root and copy the structure as mentioned below

dbmigrate
schema.rb
seeds.rbdb_statsmigrate
schema.rb
seeds.rb

The created files should be empty.

Add Rake Tasks

For handling stats database, we need to write custom tasks for creation, migrations and other functionalities.

Create a file lib/tasks/db_stats.rake with the below content

namespace :stats do

namespace :db do |ns|

task :drop do
Rake::Task[“db:drop”].invoke
end

task :create do
Rake::Task[“db:create”].invoke
end

task :setup do
Rake::Task[“db:setup”].invoke
end

task :migrate do
Rake::Task[“db:migrate”].invoke
end

task :rollback do
Rake::Task[“db:rollback”].invoke
end

task :seed do
Rake::Task[“db:seed”].invoke
end

task :version do
Rake::Task[“db:version”].invoke
end

namespace :schema do
task :load do
Rake::Task[“db:schema:load”].invoke
end

task :dump do
Rake::Task[“db:schema:dump”].invoke
end
end

namespace :test do
task :prepare do
Rake::Task[“db:test:prepare”].invoke
end
end

# append and prepend proper tasks to all the tasks as defined above

ns.tasks.each do |task|
task.enhance [“stats:set_custom_config”] do
Rake::Task[“stats:revert_to_original_config”].invoke
end
end
end

task :set_custom_config do

# save current vars

@original_config = {
env_schema: ENV[‘SCHEMA’],
config: Rails.application.config.dup
}

# set config variables for custom database

ENV[‘SCHEMA’] =db_stats/schema.rb”
Rails.application.config.paths[‘db’] = [“db_stats”]
Rails.application.config.paths[‘db/migrate’] = [“db_stats/migrate”]
Rails.application.config.paths[‘db/seeds’] = [“db_stats/seeds.rb”]
Rails.application.config.paths[‘config/database’] = [“config/database_stats.yml”]
end

task :revert_to_original_config do
# reset config variables to original values
ENV[‘SCHEMA’] = @original_config[:env_schema]
Rails.application.config = @original_config[:config]
end
end

Once all of this setup is done, we can create the stats database and run its first migration:

$ rake stats:db:create
$ rake stats:db:migrate

This will generate the Stats database schema file in db_stats/schema.rb.

Add a custom migration generator We cannot use rails generator because the path hardcodes the db/migrate. Read more From Here http://goo.gl/jVCVRJ

September 13, 2016 - (v3.2.1 - v4.2.7)
0 thanks

Search Kick Gem – To Make Your Search Intelligent On Rails App

Search kick Gem is a Ruby gem that runs on top of Elasticsearch and makes it easy to make searches in a Rails-friendly fashion. In addition, it allows you to add more features including analytics, autocomplete, and personalized results. Searchkick realizes what your users are searching for. As more individuals hunt, it gets more brilliant and the outcomes improve. It’s benevolent for designers – and supernatural for your users. It handles stemming, special characters, extra whitespace, misspellings, custom synonyms. To get started, make sure that you have Elasticsearch installed on your home computer. Depending on your operating system, the installation process is slightly different and make sure you have at least Java 7. Once you have that done, add and install searchick to your Rails application by adding the following to your Gemfile and running bundle install.

gemsearchkick’

When you have both installed and ready to go, you need to indicate which models you might want to be able to search through in your application. Just add searchkick to the model file to make it work. Then, we need to reindex the models so that Elasticsearch can run properly. In your terminal, run:

rake searchkick:reindex:all

Seeking with searchkick is entirely straightforward. Basically run YourModel.search, trailed by the parameters of the search and any filters that you want to add on. For instance, one of more complex searches is below:

 @offers = Offer.search params[:search],
 page: params[:page], per_page: 10,
 order: {starttime: :desc},
 fields: [{offer_name: :word_start}, 
 {            
offer_request_name: :word_start}:price],
 where: {
 starttime: {
 gte: DateTime.strptime(params[:fromdate],‘%m/%d%Y’),
 lte: DateTime.strptime(params[:todate],‘%m/%d/%)
 }
 }

In this search, we take the search query of the user with params[:search], and look through of the lessons with the following conditions:

Read More From Here : http://www.railscarma.com/blog/technical-articles/search-kick-gem-to-make-your-search-intelligent-on-rails-app/

September 8, 2016
0 thanks

How to use Acts_As_Votable Gem

Acts_As_Votable is ruby gem specifically written for Rails/ActiveRecord models and This gem allows any model to be voted on upvote/downvote like/dislike, etc. It allows any model to be voted under arbitrary scopes using this gem we can vote any model. votes do not have to come from a user, they can come from any model (such as a Group or Team) and it provide an easy to write/read syntax.

Gem Installation

gemacts_as_votable’

Add above line in Gemfile and run bundle install

Supported ruby and rails versions

Ruby 1.8.7, 1.9.2, 1.9.3, 2.0.0, 2.1.0
Rails 3.0, 3.1, 3.2, 4.0, 4.1+

This Gem uses vote table to save all voting information. To generate vote migration run below commands

rails generate acts_as_votable:migration
rake db:migrate

To rate any model just use “acts_as_votable” in model

Example:

class Article < ActiveRecord::Base
acts_as_votable
end

@article = Article.new(:name =>my new article’)
@article.save

@article.liked_by @user
@article.votes_for.size # => 1

Read More From Here http://goo.gl/emtP8K

September 1, 2016
0 thanks

Previewing Emails in Rails Applications With the Mail_View Gem

Sending an email from an application through a development or staging environment can be cumbersome especially when you want to preview the mail before you hit the send button. With the gem ‘mail_view, you can easily preview emails right from your development environment. Previewing mail is important to ensure that you are sending the right email and to the right person.

Never send a mail in dark anymore with the ‘mail_view gem! Check out more below on how it can be implemented in your application during the development stage.

Rails Email Preview helps us to quickly view the email in web browser in development mode.

  1. Add “gem ‘rails_email_preview’, ‘~> 0.2.29’ “ to gem file and bundle install.

  2. Run “rails g rails_email_preview:install” this creates initializer in config folder and add routes.

  3. Run “rails g rails_email_preview:update_previews” this crates mailer_previews folder in app directory.

Generator will add a stub to each of your emails, then u populate the stub with mock data.

Ex:

class UserMailerPreview
def invitation
UserMailer.invitation mock_user(‘Alice’), mock_user(‘Bob’)
end

def welcome
UserMailer.welcome mock_user
end

private
def mock_user(name =Bill Gates’)
fake_id User.new(name: name, email:user#{rand 100}@test.com”)
end

def fake_id(obj)
obj.define_singleton_method(:id) { 123 + rand(100) }
obj
end
end
  1. Parameters in search query will be available as an instance variable to preview class.

Ex: if we have a URL like “/emails/user_mailer_preview-welcome?user_id=1” @user_id is defined in welcome method of UserMailerPreview it helps us to send mail to specific user.

class UserMailerPreview
def welcome
user = @user_id ? User.find(@user_id) : mock_user
UserMailer.welcome(user)
end
end
  1. To access REP url’s like this

    rails_email_preview.rep_root_url
    rails_email_preview.rep_emails_url
    rails_email_preview.rep_email_url(‘user_mailer-welcome’)
    
  2. We can send emails via REP, this will use environment mailer settings. Uncomment this line in the initializer to disable sending mail in test environment.

    config.enable_send_email = false
    

References :

  1. github.com/glebm/rails_email_preview

  2. richonrails.com/articles/action-mailer-previews-in-ruby-on-rails-4-1

Read More From Here>>> http://goo.gl/KQBk5S

August 24, 2016
0 thanks

Scheduling Recurring Events with Ice Cube Gem

Ice_cube is a ruby library for effectively taking care of repeated events (schedules). The force lies in the ability to indicate multiple rules, and have ice_cube rapidly make sense of whether the schedule falls on a specific date (.occurs_on?), or what times it happens at (.occurrences, .first, .all_occurrences).

How to get ice cube

For install use the below syntax

gem install

if you want to get the code

gem clone git://github.com/seejohnrun/ice_cube

For creating icecube schedule

schedule = IceCube::Schedule.new
if we want to speciy startdate and enddate we have option to specify in the above mentioned schedule

schedule = IceCube::Schedule.new(start = Time.now, :end_time => start + 600)

Daily schedules

After creating schedule we have an option to add recurrence rule for the above mentioned schedule

consider “schedule every day” on above mentioned time

schedule.add_recurrence_rule IceCube::Rule.daily

consider the same schedule with repeat “n” number of days

schedule.add_recurrence_rule IceCube::Rule.daily(repeat_every_n_days)

in place of repeat_every_n_days you have option to specify the number of days For Weekly Monthly & Hourly You can Read It From Here http://goo.gl/XGmXp1

August 21, 2016
1 thank

Integrate enum with PostgreSQL Enumerated Types

Extract from:

http://www.sitepoint.com/enumerated-types-with-activerecord-and-postgresql/

There are 2 things that we need to do before we can use ActiveRecord::Enum with PostgreSQL Enumerated Types: database migration and enum declaration.

First, let’s create the database migration:

$ bundle exec rails generate migration AddGenderToUsers gender:gender

Next, edit the generated migration to add the type:

# db/migrate/20150619131527_add_gender_to_users.rb
class AddGenderToUsers < ActiveRecord::Migration
  def up
    execute <<-SQL
      CREATE TYPE gender AS ENUM ('male', 'female', 'not_sure', 'prefer_not_to_disclose');
    SQL

    add_column :users, :gender, :gender, index: true
  end

  def down
    remove_column :users, :gender

    execute <<-SQL
      DROP TYPE gender;
    SQL
  end
end

Once you’re finished with that, run the migration:

$ bundle exec rake db:migrate

Now, we have completed the database migration. The next step is to declare an enum in the User model. Earlier, we used both the Array and Hash forms to declare an enum. For the integration to work, we need to declare an enum using the Hash form:

# app/models/user.rb
class User < ActiveRecord::Base
  enum gender: {
    male:                   'male',
    female:                 'female',
    not_sure:               'not_sure',
    prefer_not_to_disclose: 'prefer_not_to_disclose'
  }
end

Finally, we can store ActiveRecord::Enum values using PostgreSQL Enumerated Types. As a bonus, all helper methods provided by ActiveRecord::Enum still work as expected.

August 18, 2016
0 thanks

Volt Framework for Ruby

Volt – a new Framework for Ruby where both the server and client sides are written in Ruby via OPAL (a ruby to JavaScript compiler) so developer can write dynamic applications without writing a single JavaScript code. Volt is similar to Meteor but it doesn’t have all the portions of Meteor.

The Basic Setup for Volt Framework

Let us install Volt and create an empty app. Make sure that you have ruby (>2.1.0) and ruby gems installed.

Install Volt Gem :

gem install volt

We can create a new project using the volt gem:

volt new sample_project

Fire up the web server:

bundle exec volt server

We can access the Volt console with:

bundle exec volt console

The Opal Compiler

Volt applications run Ruby on both frontend and backend. So the puts statement in a controller action appears in browser window and not in terminal console. And also writing Ruby code for the front end with Volt is very easy. The opal compiler translates Ruby to JavaScript. Amazing thing about it is that there is no compilation process to follow and no build tools to install. When you run volt server, everything takes place in the background. No refresh or restart is needed when you do changes to code and data.

Calling a JavaScript alert with Ruby

# Calling JavaScript functions in Ruby
module Main
class MainController < Volt::ModelController
# Called from front end when “todos” route loads.
def todos
alerttotes amaze’
end
end
end

Easy Syncing via Reactive Models

Concentrate more on this part when learning volt. Volt::Model acts as hash-like Ruby objects that sync between the front end and back end simultaneously. Usually, updates to the model happens automatically. The concept of “stores” in Volt is used to sync application data in persistent and non-persistent forms. And also a uniform means of syncing data between local storage, MangoDB, cookies, sessions and URL params.

Let’s check how to create real-time chat app of Ruby and HTML:

# Create a persistent data model. This gets stored in MongoDB.
class ChatMessage < Volt::Model
end

View Code:

<:Body>
<form e-submit=”say”>
<input class=”form-control”
type=”text”
value=”{{ page._input }}” />
</form>
<ul>
{{ _chat_messages.each do |msg| }}
<ul>
<button e-click=”msg.destroy”>X</button>
{{ msg._text }}
</ul>
{{ end }}
</ul>

Full HTTP Endpoint Support

Volt is not only for real-time framework. It also provides workflows for traditional HTTP application development. Checkout an example from GitHub :

# Routes for HTTP endpoint
get/simple_http’,
controller:simple_http’, action:index’

get/simple_http/store’,
controller:simple_http’, action:show’

post/simple_http/upload’,
controller:simple_http’, action:upload’

# Example controller

class SimpleHttpController < Volt::HttpController
def index
render text:this is just some text’
end

def show
render text:You had me at “\
“#{store._simple_http_tests.first._name}”
end

def upload
uploaded = params[:file][:tempfile]
File.open(‘tmp/uploaded_file’,wb’) do |f|
f.write(uploaded.read)
end
render text:Thanks for uploading’
end
end
August 18, 2016
0 thanks

Top 10 Tools/Ruby Gems for Quickly Building Social Networking Sites

The world is social. Where art thou? In the attention-drive world, social media rules the roost. So, it is no wonder if you have been bitten by the social networking bug and want to develop a social networking site. If you are contemplating the best platform for developing a social media site, then Ruby on Rails is an ideal option. Not only, Ruby on Rails offer you rapid development, it comes packed with a horde of gems to make the work even easier. Check out some of the best Ruby gems for building social networking websites:

Read It From Here: http://goo.gl/3OVVQY

July 25, 2016
0 thanks

Application Performance Monitoring with New Relic

The New Relic Ruby Agent runs in one of two modes:

Production Mode Low overhead instrumentation that captures detailed information on your application running in production and transmits them to newrelic.com where you can monitor them in real time.

Developer Mode

A Rack middleware that maps /newrelic to an application for showing detailed performance metrics on a page by page basis. Installed automatically in Rails applications.

NewRelic Setup

To add ruby-agent to your project add the gem in your gemfile

gemnewrelic_rpm’

Create an account in newrelic.com. You will get a 30 day free trial version

Once you signup download newrelic.yml file

Copy and paste the file in your project config folder

Project/config/newrelic.yml

Installation

Bundle install (after adding gem into gemfile)

Rails 2.x without bundler

config.gemnewrelic_rpm” (In environment.rb)

After installation of newrelic go to the newrelic.yml and look into it by default you will get

Development, test, staging and production environments

You can change/add the environment name like staging can change it to uat.

You can find developer_mode only for development environment, so what is developer_mode?

developer_mode:

New Relic Agent will present performance information on the last 100 transactions you have executed since starting the mongrel

NOTE: There is substantial overhead when running in developer mode (Do not use for production or load testing.)

To view the performance information including SQL statement

localhost:3000/newrelic (If your application is running in port 3000)

Set the application name for your required environment, so that the application name will be appearing on your newrelic dashboard and it will be easy to monitor without the name ambiguity

For example:

production:

<<: *default_settings

monitor_mode: true

app_name: Sample_Project

So when you open NewRelic dashboard you can find Sample_Project under Name column, click on it to see all the transactions.

Advantage of NewRelic Monitoring:

The main advantage of newrelic is Application Performance Management (APM).
New Relic APM is the only tool you’ll need to see everything in your Ruby application from the end user experience to server monitoring. Trace slow database queries, 3rd party APIs and web services, caching layers, background jobs, and more. Ruby monitoring has never been easier.
Error Rate: the agent collects and reports all uncaught exceptions by default.
Transaction history with graphs.
SQL Query in Transaction block.
You can also find most time consuming methods, what is making it slow.
You can also trace background-jobs.
Every time you’re working on the performance of your application, it’s always good to know what kind of effect does a particular deploy has on the performance of the application. To understand the effect, you can notify New Relic when you are performing a deployment. This way if performance degrades or improves by setting key transactions, you will get to know and then measures could be taken to improve the performance.

Newrelic is a complete tool to monitor your application and quickly response on the errors and help in serving end users in an optimized way. http://www.railscarma.com/blog/technical-articles/application-performance-monitoring-with-new-relic/

July 19, 2016 - (v4.2.1)
0 thanks

A Detailed Look at Rails 5 Features and Changes

Rails 5 was announced by David Heinemeier Hansson(DHH), creator of Ruby on Rails Framework at RailsConf 2015 in Atlanta. Ruby 5.0.0 Beta version was released on 18th December 2015. Apart from the Rails 4, the new features are implemented in 5 version such as Action cable and improved turbolinks that can instantly improve the web development workflow. Here are the Rails 5 Features : Ruby Version Support :

Rails 5 will only work on Ruby 2.2.1 and above. The following features are the reasons for using ruby 2 or higher :

Symbol Garbage Collector

In Ruby On Rails applications, we usually pass symbols all over the place, doing this opens the possibility of DoS attacks when our memory is consumed by symbols that never get garbage collected. Ruby 2.2.0 introduced changes in its garbage collector to be able to collect symbols.

Module #prepend

Allows to do insert a module in-front of the class it was prepended.

Keyword Arguments

Ruby 2.0 introduced first-class support for keyword arguments:

def foo(bar:default’)
puts bar
end

foo # => ‘default’
foo(bar:baz’) # => ‘baz’
Incremental GC

This will help to reduce memory consumption by Rails applications. Deprecated code removed and Cleanup

Action Mailer

#deliver and #deliver! methods have been removed, use new methods deliver_now or deliver_later.

*_path helper in email views has been removed and use *_url.

Active Record

Protected attributes(attr_accessible) completely unsupported now.

Unsupport for activerecord-deprecated_finders gem.

ActionPack Assertions

assert_template and assigns() assertions are deprecated and moved into its own gem rails-controller-testing.

ActiveRecord::Base#has_secure_token

Rails 5 has introduced has_secure_token to include random token in models.

Action View

In action view, helper methods such as content_tag_for and div_for were removed from the core and moved out to a separate gem record-tag-helper.

Turbolinks

New Turbolinks 3 solves one of the major problems of Rails. Few web apps works really slow cause it reloads the full page from server. This new Turbolinks 3 reloads only the contents of the body, it doesn’t reloads the whole page. It allows you to specify which elements to replace through partials.

Partial replacement feature, is the one of the most significant change in Rails 5. We will be able tell Turbolinks from client side that what content do we need to change/replace and what we don’t. To decide the replacement strategy in DOM, turbolinks will look for HTML5 custom attributes data-turbolinks-permanent and data-turbolinks-temporary.

We can use turbolinks.visit or Turbolinks.replace to update DOM and to trigger a replacement in the client side. Visit will issue a GET to the server to obtain the HTML that must be used to replace our DOM and replace expects from us the HTML that should be used for its operation.

The same functionalities can be triggered from the server-side with redirect_to and render, both redirect_to and render can receive change, keep and flush as options. But redirect_to can also receive turbolinks with true or false to force a redirect.

Action Cable

Action Cable is a framework, used to extend Rails via Websockets to add real-time message passing functionality. This is probably one of the best things in Rails 5. It smoothly integrates WebSockets with the rest of Rails application. Action cable makes it very easy to add realtime features to your app. The reason behind adding this feature was increasing need for such feature. It was introduced to extend Rails functionality with real time messaging utilizing WebSockets.

Action Cable offers a lot of advantages including being an open connection, extremely lightweight compared to other HTTP request. Another advantage is that once a connection made, it will remain open. Through that open line, both server and the client can communicate without reestablishing a new connection. The server and the client can use full-duplex connection of WebSocket to communicate to each other at the same time.

One disadvantage of Action Cable is its inability to cache requests. Another con of WebSocket is the support among browsers as only 70% of the browser market allows for WebSocket connections.

Additional New Features in Rails 5

#or method in ActiveRecord::Relation
#belongs_to is required by default
Active Record Attribute API
has_secure_token landed in ActiveRecord
Mysql active record adapter gets Json support
Render a template outside the controller
Better Minitest Test Runner

Rails API

It allows you to generate API – only Rails app and cleans out all the middleware which is not necessary in an app. When you create a new Rails application using new rails API, you will get the configuration which assumes you are working with JSON not with HTML.

Command to Create Rails API Application:

rails new my-app-apiapi

Render From Anywhere

All these days we have been using gems like render_anywhere to render views outside of controller. In Rails 5 you can render your views from anywhere. Along with the rendering options, there is also an option available for passing instant variables to templates.

Restart your App with a Rake Command

In Rail 5, you can restart all your apps with the command rake restart. And for migration: rails db:migrate Note that this list is not conclusive and to know more about all the changes in Rails 5, we recommend you to check out the release announcement on Rails.Org.

July 16, 2016
0 thanks

How to Add Functionality to Ruby Classes with Decorators

Decorators allow us to add behavior to objects in runtime and don’t affect other objects of the class. Decorators can be applied when you need to dynamically add and remove responsibility to a class. The decorator pattern is a helpful alternative to creating sub-classes. They give additional functionality to a class while still keeping the public API consistent. Let’s look at an example to understand the importance of Ruby Decorators.

consider we have a Tattoo class with a price method that returns 300.

Class Tattoo
def price
300
end
end

Now we will add an extra color as a feature, and the price would be increased by 150

The simplest way is to create a TattooWithColour subclass that returns 450 in the price method.

class TattooWithColour < Tattoo
def price
450
end
end

Next, we need to represent a big tattoo that adds 200 to the price of our tattoos. We can represent this using a BigTattoo subclass of Tattoo.

class BigTattoo < Tattoo
def price
500
end
end

We could also have bigger sized tattoos and they may add further price to our BigTattoo. If we were to consider that these tattoos types could be used with colours, we would need to add BigTattooWithColour and BiggerTattooWithColour subclasses.

With this method, we end up with total of 6 classes. Even Double that the number if you want to represent these combinations with extra designs on tattoo. Inheriting dynamically with modules

To simplify our code, we may use modules to dynamically add behavior to our Tattoo class. Let’s write ColourTattoo and BigTattoo modules for this.

module ColourTattoo
def price
super + 150
end
end

module BigTattoo
def price
super + 200
end
end

Now we can extend our tattoo objects dynamically using the Object#extend method.

tattoo = Tattoo.new tattoo.extend(ColourTattoo) tattoo.extend(BigTattoo)

This is good improvement over our inheritance based implementation. Instead of having sub classes, we just have one class and 3 modules. If we needed to add extra design to the equation, we need just four modules instead of 12 classes. Applying the decorator pattern

This module based solution has simplified our code greatly, but we can still improve it by using the decorator. We will consider a BiggerTatto as being formed by twice adding 150 to the cost of a Tattoo.

We can’t do this by our module based approach. It would be tempting to call tattoo.extend(BigTattoo) twice to get BiggerTattoo. Extending module second time has no effect when we have already used extend ones.

If we were to continue using the same implementation, we would need to have a BiggerTattoo module that returns super + 300 as the cost. Instead, we can use decorator that can be composed to build complex objects. We start with a decorator called BigTattoo that is a wrapper around a Tattoo object.

class BigTatto
def initialize(tattoo)
@tattoo = tattoo
end

def price
@tattoo.price + 150
end
end

Bigger Tattoo can now be created by using this wrapper twice on a Tattoo object.

tattoo = Tattoo.new big_tattoo= BigTattoo.new(tattoo) bigger_tattoo = BigTattoo.new(big_tattoo)

We can similarly represent colour tattoo using a TattooWithColour decorator. Using just three classes, we are now able to represent 6 types of tattoo.

Read More From Here http://www.railscarma.com/blog/technical-articles/step-step-guide-building-first-ruby-gem/

July 13, 2016
0 thanks

How to translate JavaScript strings in Rails

Rails I18n and elegant message passing to JavaScript

The process of “internationalization” usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of “localization” means to provide translations and localized formats for these bits. How I18n in Ruby on Rails Works

❝The limits of my language are the limits of my world.❞ ‒Ludwig Wittgenstein. With over 6,909 distinct languages in the world and most of them differing in so many different ways (e.g. in pluralization rules), it is difficult to provide specific tools for internalization. However, for unrestricted barriers of languages, Rails I18n API focuses on:

providing support for English and similar languages out of the box
making it easy to customize and extend everything for other languages

As part of this solution, every static string in the Rails framework – e.g. Active Record validation messages, time and date formats – has been internationalized, so localization of a Rails application means “over-riding” these defaults.

1.1 The Overall Architecture of the Library

Thus, the Ruby I18n gem is split into two parts:

The public API of the i18n frameworka Ruby module with public methods that define how the library works
A default backend (which is intentionally named Simple backend) that implements these methods

As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.

Here, the simplest way to implement internationalization in JavaScript;

a) Use the Script

<script type=”text/javascript”>
window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>
</script>

b) You can add the below code in JS file;

I18n[“en-US”][“alpha”][“welcome”];

c) Get help from the application helper by adding the below method;

def current_translations

@translations ||= I18n.backend.send(:translations)

@translations[I18n.locale].with_indifferent_access

end

d) The backend needs to be initialized if it hasn’t been already.

I18n.backend.send(:init_translations) unless I18n.backend.initialized?

# now you can safely dump the translations to json

e) Invoke the below in your application.html.erb ;

<script type=”text/javascript”>

window.I18n = <%= current_translations.to_json.html_safe %>

</script>

f) To avoid having to know the current locale in JavaScript.

I18n[“alpha”][“welcome”]; Or I18n.alpha.welcome;

g) Various libraries and plugins for Internationalization & localisation:

i18next – http://github.com/i18next/i18next

I18n gem – http://github.com/svenfuchs/i18n

requirejs-i18n – http://requirejs.org/docs/api.html#i18n

Read More :http://www.railscarma.com/blog/technical-articles/how-to-translate-javascript-strings-rails/

July 12, 2016
0 thanks

Ruby on Rails vs PHP

With more and more applications being built every day, programming languages too are becoming generic and all-purpose. Every programming language comes with its own set of specialization, and comparison between one programming languages to others may seem like a comparison between apples and oranges. However, comparison between two programming languages may offer you insights that might be crucial in your decision to go for a specific programming languages, especially when it comes to Ruby on Rails vs PHP. Since at RailsCarma, we work with both the ecosystems, we are able to understand the advantages and disadvantages of both. Here are some very simple and easy to understand comparison between Ruby on Rails and PHP.

PHP: PHP is a scripting language, used for web development to make interactive pages. The most common frameworks used for PHP are CakePHP, CodeIgnitor, Laravel, etc.

Ruby on Rails: Ruby is a scripting language and Rails is a web application framework written in Ruby.

  1. To Learn

PHP is simpler to learn as compared to Ruby especially for fresher in development. PHP codes can be easily run on server and deployed. To maintain the code, some standard needs to be followed. When it comes to frameworks, the benefit of PHP is that, it has more number of frameworks compared to Ruby. You can find more PHP developers compared to Ruby on Rails, which is really helpful for the companies or developers who need to learn the language. Documents and solutions are easily and readily available for PHP than Ruby on Rails, as applications and websites developed in PHP are more in number as compared to RoR.

  1. Resources

PHP provides lots of resources, frameworks and applications, such as WordPress, Drupal, Joomla, Magento, whereas Ruby on Rails in this department.

  1. Performance

PHP (language) is faster as compared to Ruby on Rails (framework) as it was designed only for web, but PHP is almost same or slower when it’s with frameworks like Laravel, CodeIgnitor, etc.

  1. Frameworks

Rails – The more you work on this framework, the more you will gain. It helps in providing quality products in less time when compared to PHP. Rails is a stable framework so companies and developers can easily adjust to it by learning one single framework, whereas for PHP there are a lot of frameworks which may make learning confusion. There are also no surety whether all the PHP frameworks will be supported in future or not.

  1. Development

Rails is a well-engineered framework where most of the necessary things are automated so that developer can just focus on business related work.

The points where PHP lacks are:

ScaffoldingGenerating a code in an easy and straightforward way, helps in faster development, whereas PHP lacks in this regard. However, PHP community has started work on this with FuelPHP providing similar features.
GemsRails provides plugins as a gem. Just add in your application and it fastens your development. Also, it’s easy to maintain as you are not trying to load libraries. For ex:Devise” gem which is used for authentication can be just installed in an application to handle all the processes.
ORMActiveRecord in the Ruby on Rails is the best part where you can perform all the database related queries using Ruby. Although PHP frameworks too provide the same but not up to the level of Ruby on Rails.
  1. Testing

Rails has testing frameworks that can be used to test your code and provide bug free code and make the client happy, where PHP framework are still trying to get this feature. PHPUnit is one such example.

  1. Cost

Development in PHP is much cheaper as compared to development in Ruby on Rails. Since, PHP is easier to learn and implement, it has more developers and so because of resources vs demand scale, it is cheaper to get your website developed in PHP as compared to Ruby on Rails.

Conclusion PHP has very large developer pool, it is easy to learn, has too many framework to choose, can find easy solution with the availability of experienced developers and is affordable. Ruby on Rails has passionate community, is always introducing new changes, application will be quick to market and best suits for agile development.

July 12, 2016
0 thanks

Step-By-Step Guide to Building Your First Ruby Gem

Nowadays all the functionalities in Rails are built as Ruby gems. For example we can use devise gem for the authentication part of the application. It’s like a package or library that is written in Ruby programming language. Moreover it can be imported and used by others in their programs.

Step 1 Bundler is like a dependency management tool for Ruby, which is also used by Rails. We will use Bundler for the basic gem structure. It helps us to install the correct versions of the gem and forces us to use the same in the application. So the command for that is, gem bundler install After bundling, we should specify the gem “name” that we are going to create i.e. Bundle gem “testgem” will create a repository shown below

So in this we can see the basic gem structure. Under the lib folder, version file will be used to mention the version of the Gem. We can edit the version as per our convenience and release it that will be the version in Rubygems.

Step 2 We will consider testgem.gemspec, with testgem as the name of the gem that we will create for sample. It will be used to set up the gem on rubgems, for e.g., name of the gem, summary, description, files that are required in this project, test files that are used to testing the files in the project etc.

Rake file: – This makes releasing the new versions of the gem, and also helps other developers to check the test cases if they are going to modify the particular gem. After the rake, we should create a test folder and test cases for each segments will be included here in the app directory.

Step 3 Planning to make a rubygem, then we need to analyse the requirements what to build up and what all functionalities should be included in that. While generating, we should create a sample.rb file inside lib folder and create own class with namespace because the other plugin has also the same classes then it will get conflict in the names. And require the sample.rb file in the testgem.rb file like reqiure “testgem/sample”.

Step 4 We have require “bundler/gem_tasks” in rake file so when we run rake release, it will release the gem to ruby gems and make it available. Push to git repository

June 8, 2016
0 thanks

SOCKET LIBRARY IN RUBY ON RAILS

There are basically two levels of accessing network services in case of rails .

The socket and network libraries are such important parts of integrating Ruby applications with the Internet and other communications-based environments.

One is through socket libraries provide low level access to connection oriented and connection-less protocols. Where user can implement client and server connection. Ruby is also having Network libraries that provide users a high level access to specific network protocols like FTP,HTTP and Etc.

At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols. Ruby also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.

What are Sockets?

Sockets are basically a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. Sockets can be implemented on different channels : Unix domain sockets, TCP, UDP, and so on. The socket library mainly provides specific classes and interface for handling a transports.

A SimpleClient:

Hereis a very basic client program which will open up a connection to a given port and given host. Ruby class TCPSocket provides open function to open a socket. The TCPSocket.open(hosname, port ) opens a TCP connection to hostname & theport.

Once socket is open, you can actually read that particular thing like IO object. When it’s done, just remember to close it, as you close that file. The following code connects to a given host and port, reads any available data from the socket, and then exits:

require ‘socket’ # Socket in standard library

hostname = ‘localhost’

port = 8080

s = TCPSocket.open(hostname, port)

while line = s.gets # Gets and Read the lines from the socket

puts line.chop # And print with platform line terminator end

s.close # socket Closed

A Simple Server: To write Internet servers, we basically use this TCPServer class. A TCPServer object is a factory for TCPSocket objects. Now call TCPServer.open(hostname, port function to specify a port for your service and create a TCPServer object. Next, call the accept method of the returned TCPServer object. This particular method waits till client connects to the port you specified above, and then returns a TCPSocket object that basically represents the connection to that client.

require ‘socket’ # Get sockets from stdlib server = TCPServer.open(8080) # Socket to listen on port 8080 loop { # Servers run forever

client = server.accept       # Wait for a client to connect
client.puts(Time.now.ctime)  # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close                 # Disconnect from the client

}

Now run this server in background and then run above client to see the result.

June 7, 2016
0 thanks

foreign_key option

It is also possible to specify that add_foreign_key should be added to the schema:

add_reference(:products, :supplier, foreign_key: true)
May 25, 2016
0 thanks

Active Record Import

With activerecord-import, you’d just add your records to an array and call import:

records_to_import = pricing_data.map do |location, price|
  Inventory.new(location: location, price: price) 
end

Inventory.import records_to_import 
May 25, 2016
0 thanks
May 25, 2016 - (v1.0.0 - v3.1.0)
0 thanks
May 19, 2016 - (>= v4.1.8)
0 thanks

Careful with arel column

I use what @equivalent suggests a lot but be careful, you MUST state the direction otherwise methods like take/last/first will fail silently!

StatusChange.arel_table[‘created_at’]. asc

not:

StatusChange.arel_table[‘created_at’]

May 5, 2016
0 thanks

more loops

fruits = [‘apple’,‘orange”]

fruits.each do |fruit|

puts "A fruit of type: #{fruit}"

end