Flowdock

Notes posted to Ruby

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/

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

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

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 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
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 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

May 5, 2016
0 thanks

more loops

fruits = [‘apple’,‘orange”]

fruits.each do |fruit|

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

end

May 4, 2016 - (v1_9_3_392)
0 thanks
February 12, 2016
0 thanks

group on hash

def group_by_hash hash, value
  hash.group_by do |k,v| 
    v > value ? "Big" : "Small"
  end
end

marks = {"Chair" => 30, "Table" => 40, "Bed" => 60, "stool" => 20}
group_by_hash(marks, 30)
February 4, 2016
0 thanks

Fetch with default value

You can specify default value as a fail-back if a hash doesn’t have a given key.

{a: false}.fetch(:b, true)
=> true
{a: false}.fetch(:a, true)
=> false

It is useful especially in the case where you want to set default value for a method.

def initialize(args)
  @foo = args.fetch(:foo, 1)
  @bar = args.fetch(:bar, 2)

  # This can take over the following way.
  # `@bar = args[:bar] || 2` 
  # => @bar is overwritten if caller specifies nil for :bar!
end
January 22, 2016
0 thanks

Errno::EEXIST

When Errno::EEXIST is raised, it indicates there are permission issues, rather than an existing item.

January 4, 2016 - (>= v1_9_3_392)
0 thanks

Also implemented by other classes

It’s worth noting that this method is also implemented by other classes like Proc, Range and even String.

Most of these are missing proper examples, but you can find some useful examples here:

http://www.blackbytes.info/2015/10/ruby-case/

November 17, 2015
0 thanks

Find and Detech are the same

@rubynooby: #find and #detect are aliases of the same underlying method. You can use them interchangeably to provide additional readability to your code (find an element to use it or detect if an element is present to do something).

http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-find

November 13, 2015 - (v1_9_3_125 - v1_9_3_392)
0 thanks

What you really want is

The official Ruby documentation is available for this here http://ruby-doc.org/stdlib-2.2.3/libdoc/rss/rdoc/RSS.html

But the library that will be most helpful to you is called Feedjira: http://feedjira.com/

November 3, 2015
1 thank

Re: close but no bananna

Actually, @tarasevich is right on this. Let’s have a look at your own example:

[["1","2"],["3","4"]].flat_map {|i| i[0] }     # => ["1", "3"]

[["1","2"],["3","4"]].map {|i| i[0] }.flatten  # => ["1", "3"]
[["1","2"],["3","4"]].flatten.map {|i| i[0] }  # => ["1", "2", "3", "4"]

You are right that both #map and #flatten are non-commutative, it does matter which method is called first.

But #flat_map is equivalent to mapping first and then concatenating (flatten) the results, even if the name might suggest the opposite.

To correctly interpret the method name, you should think of it mathematically as a function composition.

November 3, 2015 - (>= v1_9_2_180)
0 thanks

close but no bananna

@tarasevich noted that

a.flat_map(&b) works exactly like a.map(&b).flatten!(1)

This is backwards because map and flatten are not always interchangeable in order. Mapping over the example array only gives you 2 items. This can result in significant differences depending on what you’re doing in the map. This is easier to demonstrate if we change the example to strings.

[["1","2"],["3","4"]].map {|i| i[0] } # => ["1", "3"]
[["1","2"],["3","4"]].map {|i| i[0] }.flatten  # => ["1", "3"]

BUT if you swap the order

[["1","2"],["3","4"]].flatten.map {|i| i[0] } # => ["1", "2", "3", "4"]

in order to remember what it is equivalent to just note that the method name is already in the correct order. flat_map -> flatten + map

September 14, 2015 - (v1_9_1_378 - v1_9_3_392)
0 thanks

Getting the return value from the underlying method of an Enumerator

This is documented in the example code, but easy to miss.

When you get an Enumerator using #to_enum(:method_name, …), you can get all of the yielded values using #next, but not the value that is finally returned.

That value can be retrieved via the #result attribute of the StopIteration exception object that is raised when calling #next after the underlying method has returned.

August 18, 2015
0 thanks

Add method to instacne eval

We can add method to instance by using instance_eval.

Code example

string = "String"
string.instance_eval do
  def new_method
    self.reverse
  end
end

Output

irb(main):033:0> string.new_method
=> "gnirtS"
August 3, 2015
1 thank

define_method with default parameters

To define a method with a default parameter the usual notation can be used:

define_method("example") do |fixed, default = {}|
  # something
end
July 31, 2015
0 thanks

Also takes a block

You can define methods within a block

User = Struct.new(:first_name, :last_name) do
  def full_name
    "#{first_name} #{last_name}"
  end
end

user = User.new('Simon', 'Templar') # => #<struct User first_name="Simon", last_name="Templar">
user.full_name # => "Simon Templar"
July 13, 2015
0 thanks

Correction to previous comment

You’ve misread the documentation, @sandyjoins. If you pass two arguments, the second one is a length argument, not an upper bound.

“Hello there”.byteslice(6, 1) == “t”

July 13, 2015 - (v1_9_3_392)
0 thanks

Important note!

Special cases:

Code example

Test”.byteslice(1, 3) => “est” #both limits inclusive

Test”.byteslice(0, 3) => “Tes” #upper limit exclusive

Test”.byteslice(0..3) => “Test” # Both limits inclusive

May 23, 2015 - (v1_9_3_392)
0 thanks

Constants

Reading source one can find detailed patterns: github.com/ruby/ruby/blob/ruby_1_9_3/lib/uri/common.rb

May 22, 2015 - (>= v1_8_6_287)
0 thanks

Not exactly like map {}.flatten

To also give dimension, is about 4.5 times faster then map {}.flatten.

May 12, 2015
0 thanks

RE: Convert an Array of Arrays to a Hash using inject

Another way to convert an array of arrays to a hash using inject:

array = [['A', 'a'], ['B', 'b'], ['C', 'c']]

hash = array.inject({}) do |memo, values|
  memo.merge!(values.first => values.last)
end

hash
# => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
May 1, 2015
6 thanks

Very bad documentation

This is terrible documentation. It makes it very hard to understand what the arguments mean.

The signature is

alias_method(p1, p2)

So what do p1 and p2 mean? The description doesn’t refer to them at all, but to new_name and old_name. How are we supposed to know which is which?

And then it gets even worse in the code sample:

alias_method :orig_exit, :exit

From the naming it sounds like the first argument is the original method name.

Documentation is supposed to resolve this kind of confusion, not create it.

April 29, 2015
0 thanks

Prevent new line character.

To prevent the “\n” character added at the end of each file pass in the “row_sep: nil” option:

[ "some", "array" ].to_csv                 # => "some, array\n"  

[ "some", "array" ].to_csv( row_sep: nil ) # => "some, array"
April 21, 2015
0 thanks

RSS feeds in Rails

Fetching RSS feeds in the request/response cycle inside a Rails application is probably not the very best approach, as it will make your application as slow as the server serving RSS feeds. Another option is to do it asynchronously using a worker or a queue, but this can also become quite complex and hard to maintain over time.

Another solution is to use an API like superfeedr.com and its Rails Engine (http://blog.superfeedr.com/consuming-rss-feeds-rails/). All the polling and parsing is done on Superfeedr’s side and your application is notified in realtime as soon as the resources are updated using a webhook pattern.