APIdock / Ruby
/
method

alias_method

v1_9_1_378 - Show latest stable - Class: Module
alias_method(p1, p2)
private

Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.

module Mod
 alias_method  :orig_exit, :exit
 def exit(code=0)
 puts "Exiting with code #{code}"
 orig_exit(code)
 end
end
include  Mod
exit(99)

produces:

Exiting with code 99
static VALUE
rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
{
 rb_alias(mod, rb_to_id(newname), rb_to_id(oldname));
 return mod;
}

13Notes

Very bad documentation

mkopel · May 1, 20157 thanks

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.

Bad example

rkh · Apr 8, 20102 thanks

Note that it would be better to avoid the alias_method line in the example and just call super.

Perfectly applicable

nZifnab · Mar 2, 20111 thank

@rkh You would be correct if this code had occurred in a subclass who's parent method was being overridden.

However, defining the method in this manner is completely removing the old method - as if you had written code like this:

class MyClass
def do_something
 puts "We're doing some stuff here"
end
def do_something
 puts "The old do_something method no longer exists!"
end
end
MyClass.new.do_something
# => "The old do_something method no longer exists!"

Of course this is non-sensical. But the idea is that you have either included a module, or monkey-patched an already existent class, and completely replaced the old method. super(*args) will not work

Bad Example

drewyoung1 · Oct 10, 20121 thank

@nZifnab it is a bad example because an included module is basically a class.

module Mod
 def exit(code = 0)
 puts "Exiting with code #{code}"
 super
 end
end
include Mod
exit 99

produces

Exiting with code 99

@drewyoung1

npearson72 · Dec 10, 20121 thank

Including module in a class does not automatically over-write methods defined with the same name.

Ex:

module Mod def exit(code = 0) puts "Exiting with code #{code}" super end end

class OriginalClass include Mod def exit puts "Original message" end end

OriginalClass.new.exit 99

Produces:

exit': wrong number of arguments (1 for 0) (ArgumentError)

if you use this construct, the alias_method will work similar to super:

module Mod alias_method :super_exit, :exit def self.included base base.instance_eval do def exit(code = 0) puts "Exiting with code #{code}" super_exit end end end end

Volt Framework for Ruby

rubyonrailsdevelopment · Aug 18, 2016

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
alert ‘totes 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

Scheduling Recurring Events with Ice Cube Gem

rubyonrailsdevelopment · Aug 24, 2016

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

How to use Acts_As_Votable Gem

rubyonrailsdevelopment · Sep 8, 2016

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

gem ‘acts_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

Examples corrected

bparanj · Nov 10, 2016

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

Ruby Developers

rubyonrailsdevelopment · Nov 16, 2016

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
require ‘new_test_gem’
module/class NewTestGem

And:

gem gem-structure-new_test_gem
require ‘gem/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/

Code Refactoring Gem – Flay

rubyonrailsdevelopment · Dec 2, 2016

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 Cd "Path to your project folder"

flay "path 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/

Rails caching with dalli gem

rubyonrailsdevelopment · Dec 15, 2016

Dalli is a high performance pure Ruby client for accessing memcached servers. It works with memcached 1.4+ only, as it uses the newer binary protocol.

Memcache Memcached is a quick in-memory protest reserving framework that can make Rails run much quicker with not very many changes. Memcached is an in-memory key-value store for little pieces of discretionary information (strings, objects) from consequences of database calls, API calls, or page rendering.

Run the command below to install memcached On Ubuntu sudo apt-get install memcached

On Mac brew install memcached

Please refer the URL below to know more about installing memcahed https://github.com/petergoldstein/dalli#installation-and-usage

Install dalli gem gem 'dalli'

Add the gem above to your gemfile and run bundle install.

Configuration Here, we have to configure our rails app to serve caching mechanisam. Add below line to the production.rb(config/environments/production.rb) config.cache_store = :dalli_store

Dalli::Client accepts the following options. All times are in seconds. expires_in: Global default for key TTL. Default is 0, which means no expiry. namespace: By default, it is nil. It’s prepend to each key if you specify namespace. failover: Default is true. Boolean, if true, Dalli will failover to another working server if the main server for a key is down. threadsafe: Boolean. If true, Dalli ensures that only one thread is using a socket at a specified given time. Default is true. serializer: The serializer to use for objects being stored (ex. JSON). Default is Marshal. compress: Boolean, if true Dalli will gzip-compress values larger than 1K. Default is false. compression_min_size: Minimum value byte size for which to attempt compression. Default is 1K. compression_max_size: Maximum value byte size for which to attempt compression. Default is unlimited. Please check more configations at https://github.com/petergoldstein/dalli#configuration After this, we have to tell ActionController to perform caching. Add the line below to the same file and restart Rails server if you are already running it. config.action_controller.perform_caching = true

Please add the code below to your index method @posts = Rails.cache.fetch('posts', expires_in: 5.minutes){ Post.all }

Here, Rails.catche.fetch reads the data from ‘posts’ key. If the specified key has any data, it will return data otherwise it will write to that key and it will be available for successive calls within the expiry time.

Rails provides helpers such as Rails.cache.read to read the cache, Rails.cache.write to write in the cache and Rails.cache.fetch to return the results if present in the cache or else, write in the cache to return the results.

You can read more about Rails cache at http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html

Rails.cache.clear() – Flushing all the keys from memcached. Rails.cache.delete(‘posts’) – If you wish to flush any specific key from memcached server. http://www.railscarma.com/blog/technical-articles/rails-caching-dalli-gem/

Clarifying the confusing example

lazylester · Jan 5, 2017

since exit is a keyword in Ruby, the example may be confusing. The following example might be less so: module Foo begin # this raises an error b/c baz is not defined here alias_method :other_baz, :baz rescue NameError =>e puts e end

def baz
 puts "first baz called"
end
# now that baz method is defined, we can define an alias
alias_method :other_baz, :baz
# we can now overwrite baz.
# If we want the original baz, use the alias we just defined
def baz
 puts "second baz called"
end
def qux
 puts "qux called"
end
alias_method :bar, :qux
end
include Foo
# calls the second baz method, b/c it overwrites the first
baz #=> "second baz called"
# calls the first baz method, due to the alias_method making a copy
other_baz #=> "first baz called"
bar #=> "qux called"
qux #=> "qux called"

The resulting output is:

undefined method `baz' for module `Foo'
second baz called
first baz called
qux called
qux called

AltStyle によって変換されたページ (->オリジナル) /