Recent Post

Thursday, 26 April 2018

Examples: https://gist.github.com/aditya01933/c6a867e981110885369f06c5a4103644

Topics:

1. 3 pillars of ruby.
2. Classes and objects.
3. Inheritance - diving deep
4. Meta programming and reflection - diving deep.
5. Power of method missing.
6. Mixins and ducktyping
7. Super - diving deep
8. Yield
9. Closure
10. Block, proc and lambda
11. More meta programming(examples).
12. Ruby open classes.



0

3 PILLARS OF RUBY

Following are the 3 pillars of Ruby

  1. Everything is an object.
  2. Every operation is a method call on some object.
  3. Everything is metaprogramming.

1. Everything is an object (Almost)

In ruby everything you see is an object.
Lets take an example:
irb(main):001:0> 2.to_s
=> "2"
irb(main):002:0> 'hello'.to_sym
=> :hello
Here 2 and hello is also an object.
So what is the class of 2 and ‘hello’?
Let’s find out
irb(main):005:0> 2.class
=> Fixnum
irb(main):006:0> ‘hello’.class
=> String
As you can see, even data types are the objects of some pre-defined classes.
What about nil?
Let’s find out
irb(main):009:0> nil.class
=> NilClass
Even nilis an object of class NilClass😅
Why (Almost)?
There are some things that are not purely object in Ruby like keywords like ifalias, and beginendrescue are not object in ruby.
Also, it’s worth noting that everything or every statement evaluates to an object.

2. Every operation is a method call on some object

Every operation you see is a method call on some object. Ruby provides you syntactic sugar to make the statement more intuitive. Let’s take some examples:
The simple statement
irb(main):001:0> 1 + 2
=> 3
can be re-written as
irb(main):001:0> 1.+(2)
=> 3
In this example we are calling + method on Fixnum object and passing 2 as an argument to it.
Some more examples:
1 + 2                    => 1.+(2) or 1.send(:+, 2)
my_array[4]              => my_array.[](4)
                            or my_array.send(:[], 4)
my_array[3] = "foo"      => my_array.[]=(3, ‘foo’)
if (x == 3) ....         => if (x.==(3))
my_func(z)               => self.my_func(z)
                            or self.send(:my_func, z)

3. Everything is metaprogramming.

Metaprogramming is a technique by which you can write code that writescode by itself dynamically at runtime. This means you can define methods and classes during runtime or you can manipulate methods and objects at run time.
The statement that everything is metaprogramming because even the class declaration or object initializations is the type of metaprogramming where you define new objects on existing objects.
Lets take an example:
If you go to the ruby console and run
irb(main):004:0> self.class
=> Object
you will see that self is the object of class Object. Now whatever you will define on console will become the part of Object class.
irb(main):021:0> def print_hello
irb(main):022:1> puts 'hello'
irb(main):023:1> end
=> :print_hello
irb(main):024:0> self.print_hello
hello
=> nil
As you can see, we have defined a method(called as singleton method)print_hello on pre-existing object self of class Object.
The same thing happens when you declare a class, for example:
irb(main):035:0> class Meta
irb(main):036:1> end
=> nil
irb(main):037:0> Meta.class
=> Class
Here, you are declaring a new object Meta of class Class.
That’s why what ever you write in ruby is meta-programming.
Wow!! that means you have been using Metaprogramming from the beginning without even knowing it. 😛

0

Thursday, 13 October 2016




Developers often neglect the core concepts of ruby when they start working on Rails projects.

" A good rails developer may not be a good ruby developer but a good ruby developer is always a good rails developer."

In my journey to be a good ruby developer, I am demonstrating a simple but powerful core ruby concept that can be used in rails or other ruby based projects.

You might have often seen this kind of code pattern in ruby on rails projects:

  class User
      def format_name
          do_something_with name
          do_another_thing_with name
      end

      def name
          @name ||= begin
              User.first.name
          end
      end
  end

In above code name method is called multiple times and that's why we are using memoization.

Following is another way of memoization that is using some core concepts of ruby:

  class User
      def format_name
          do_something_with name
          do_another_thing_with name
      end

      def name
          def self.name
              @name
          end
          @name = User.first.name
       end
  end

Following are the concepts behind the above code:
1. Whenever you are going to call  name method  for first time, It is going to create  Singleton method - name  for declared object.
2. Whenever you will call  Singleton method  for 2nd time, it is going to execute  Singleton - name method instead of main class  name method because  Singleton method  have high preference over main class methods.
3.  Singleton method  have access to all instance variables of an object.

Above methodology can be used when code inside  begin block is complex or large or may be in different situations to simply code.

This way also memoizes `false` and `nil` values as well: 

For example:
  class Foo < Object
      def thing1
          do_something with: expensive_computation1
          do_something_else with: expensive_computation1
      end

      def thing2
          do_something with: expensive_computation2
          do_something_else with: expensive_computation2
      end
  
  private

      def expensive_computation1
          @expensive_computation1||= Model.where(id: 1742).first
      end

      def expensive_computation2
          def self.expensive_computation2
              @expensive_computation2
          end
          @expensive_computation2= Model.where(id: 4217).first
      end
  end

 thing1  and  thing2  both are memoized but  thing2  also memoizes when the record is not found.  thing1   will go hit the db again.

Benchmark comparison of different memoization methods: 


  require "benchmark"

  class A
      def name
        @name ||= begin
                    rand
                  end
      end
   end

  class B
      def name
          return(@name) if defined?(@name)
          @name = rand
       end
  end

  class C
      def name
          def self.name
              @name
          end
          @name = rand
      end
   end

  class D
      def name
          class << self
             def name
                 @name
             end
          end
          @name = rand
      end
  end

  n = 20_000
  n1 = 2_000
  Benchmark.bm(2) do |x|
      x.report("A:") { n.times { k = A.new; n1.times { k.name } } }
      x.report("B:") { n.times { k = B.new; n1.times { k.name } } }
      x.report("C:") { n.times { k = C.new; n1.times { k.name } } }
      x.report("D:") { n.times { k = D.new; n1.times { k.name } } }
  end


Output: 


           user     system      total        real
  A:   3.810000   0.000000   3.810000 (  3.817210)
  B:   4.000000   0.010000   4.010000 (  4.007852)
  C:   2.850000   0.010000   2.860000 (  2.848843)
  D:   2.850000   0.000000   2.850000 (  2.854403)



Although there is not much difference but comparatively 'C' is fastest.
Also it's worth noting that initialisation of singleton method is slower than Boolean initialisation but calling singleton method is much faster and that make it usable.

I hope you would like this new way of memoization. Suggestions to improve the code and article are most welcome. :-)

Special Credit: My friend Brian Giaraffa , Kaushik and Philip Hallstrom :-)
5

Saturday, 1 August 2015

Crazy Material Design Examples


Material Design

Created and designed by Google, Material Design is a design language that combines the classic principles of successful design along with innovation and technology. Google's goal is to develop a system of design that allows for a unified user experience across all their products on any platform.
Material Design makes more liberal use of grid-based layouts, responsive animations and transitions, padding, and depth effects such as lighting and shadows. Designer Matías Duarte explained that, "unlike real paper, our digital material can expand and reform intelligently. Material has physical surfaces and edges. Seams and shadows provide meaning about what you can touch." Google states that their new design language is based on paper and ink.
Material Design will gradually be extended throughout Google's array of web and mobile products, providing a consistent experience across all platforms and applications. Google has also released application programming interfaces (APIs) for third-party developers to incorporate the design language into their applications.



You can read more about material design here

Following are some crazy material design examples you can use in your website.

1. Material Design Responsive Table:

Table design with material design looks awesome. Check out code by clicking below.
 

2. Material Design Buttons

Crazy look for buttons can be achived with material design.



3. Material Design Form

This is my favorite one, Form with material design.
 

4. Material Design Preloader

You can see preloader commonly in many Google apps.


 

5. Bootstrap With Material Design

You can also use bootstrap with material design check out following demo.
0

Sunday, 19 July 2015

Using Google Translate as Proxy Server

During the boring lectures, I always like to watch youtube videos or my social media accounts but my collage have blocked them.  I have seen tons of tutorials on using a cracker and using a proxy etc. But my collage blocks that too. Also, using proxy server is pain in neck as most of them are very slow. Its also not safe to login via proxy server into your social media account. So I found a way to run proxy server by using most trusted and fastest network - Google.

Ok, let's start from the beginning. We all know that Google is more than a search engine; we do use it as provider for email, mapping, news and many other services. Google is now also a free proxy service. Proxy is a device that stands between a PC and the internet, providing all the connections to the world wide web. What a proxy does is to receive all data from a requested site, so when you access web pages all data come from proxy.

Our main purpose is simple. To access blocked websites.

Here is how to use it.

Step 1: 
Open up your browser

Step 2: 


Step 3:
Enter the website URL and Translate from Spanish to English or any other language to english. That's it. Enjoy surfing....


9

Saturday, 18 July 2015

Transfer File between computer and Android using Wifi via Browser

Many people struggle to transfer files between computer and android. Today I will tell you most easy way to Transfer any kind of file and te good news is...No need to install any kind of software in computer. 

IT is only 3 Step Procedure.

Step 1: 
Download and install this Android app from playstore, IT's free....:


Its only 981kb file :)

Step 2:
Open app and Click on Start Service button.
start service wifidroid
Step 3:
Open browser in your computer and go to the url/address shown in android app.
wifidroid browser

That's it ... enjoy file transfer..
3

Location Autocomplete and Geocoding using Google APIs in Rails



Geocoder and rails autocomplete

Hello friends, Today we are going to make a web app that will help you find Aliens near your location. We will use Google Place API, GeocoderGem & Geocomplete jQuery plugin in this tutorial. 

GeoCoder Gem: If you have to work with Geographic data in your Rails applications the Geocoder gem makes this much simpler. It can convert place names to coordinates and vice-versa and even convert IP addresses to street addresses. It can also find nearby locations with their distance and bearing and has many other useful features. 

AutoComplete with GeoComplete: It is an advanced jQuery plugin that wraps the Google Maps API's Geocoding and Places Autocomplete services. You simply provide an input that lets you search for locations with a nice autocomplete dropdown. Optionally add a container to show an interactive map and a form that will be populated with the address details.

Step-1: 
Lets Start by Creating a rails Application AlienFinder
terminal
$ rails new AlienFinder

Step-2:
Once we have created the application the next thing to do is to create an Alien scaffold with name, address, latitude and longitude fields.
terminal
$ rails g scaffold Alien name:string address:string latitude:float longitude:float

Step-3:
The naming of the latitude and longitude fields is important as Geocoder will use these to store the location coordinates, although the default field names can be overridden. Both fields need to be floats. We’ll need to migrate the database to create the new aliens table.
terminal
$ rake db:migrate

Step-4: Installing Geocoder
Now we have the scaffolding set up we can create new Aliens in our database but we have to enter the latitude and longitude manually. We’ll update our application now so that these fields are filled in automatically by Geocoder.
Add Geocoder in gemfile and run bundle command.
/Gemfile
gem 'geocoder'

Step-5: Using Geocoder
Next we’ll modify our Alien model and add a call to geocoded_by to specify the attribute that we want Geocoder to convert, in this case the address.
/app/models/alien.rb
class Alien < ActiveRecord::Base
  geocoded_by :address #can also be an IP address
  after_validation :geocode
end
The geocode method sends a request to an external API, by default the Google Maps API.

Step-6:
The external API will be called every time we update an alien but this should only happen when the address field changes. We can make a simple change to the after_validation callback to implement this.
/app/models/alien.rb
class Alien < ActiveRecord::Base
  geocoded_by :address
  after_validation :geocode, :if => :address_changed?
end

Step-7:Getting nearby locations


We have a number of aliens in our database now so we’ll add this feature to our alien page.
We want to list each alien within a given distance and Geocoder makes getting nearby aliens easy with its nearbys method. By default this will return alien objects within a twenty-mile radius, but we can change it. To list the nearby aliens we just loop through each alien in @alien.nearbys and its distance in miles.
We will also add Search box where user can search for aliens near an address.
/app/views/aliens/index.html.erb
<div class="centered">
  <h1>Alien Finder</h1>
  <%= form_tag aliens_path, :method => :get do %>
    <p>
      <%= text_field_tag :search, params[:search],:id => 'geo-input' %>
      <%= submit_tag "Search Near", :name => nil %>
    </p>
  <% end %>
  <h3>Nearby Aliens</h3>
  <% @aliens.each do |alien| %>
    <p>
      <div class="res">
      <b><%= alien.name %></b></br>
         <%= alien.address %></br>
          <%= alien.distance.round(2) %> miles
      </div>
    </p>
  <% end %>
</div>
and in controller
/app/controllers/aliens_controller.rb
def index
  if params[:search].present?
    @aliens = Alien.near(params[:search])
  else
    @aliens = Alien.all
  end
end
Step-8: Autocomplete Address Search Box
Next we'll add Autocomplete feature in search box.
Download Geocmplete zip file HERE 
Extract it and copy jquery.geocomplete.js into app/assets/javascripts folder.
Now in application.js or alien.js add //= require jquery.geocomplete and following function.
/app/assets/javascript/applicaion.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require jquery.geocomplete
$(function() {
$("#geo-input").geocomplete();
});  

In application.html.erb add following lines
/app/views/layouts/application.hrml.erb
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
<script src="jquery.geocomplete.js"></script> 

Now you can see it working.
Reference RailsCast
4

Followers