Wednesday, January 27, 2016

Installing Scheme 9.2 on Mac OS 10.10.5

1. Download 64-bit installer mit-scheme-9.2-x86-64.dmg
2. Install Scheme.
3. sudo ln -s /Applications/MIT\:GNU\ Scheme.app/Contents/Resources /usr/local/lib/mit-scheme-x86-64
4. sudo ln -s /usr/local/lib/mit-scheme-x86-64/mit-scheme /usr/local/bin/scheme
5. Type scheme on the terminal.

undefined method `want=' for nil:NilClass (NoMethodError)

In Rails 4.2, you can define your own application specific custom variables in development.rb, test.rb and so on. If you define this:

  config.x.whatever.value.want = 42

It throws the error : undefined method `want=' for nil:NilClass (NoMethodError)

It seems to work only for two levels, so, this will work:

  config.x.whatever.value = 42

You can access the value like this:

Rails.configuration.x.whatever.value

You need to define the custom values by using 'config.x'.

Thursday, January 21, 2016

Error in The Well Grounded Rubyist Book

David Black says "The only circumstances under which you can omit the receiver are precisely the circumstance in which it's ok to call a private method."

 This is not true because we can omit the receiver when we call the class method declared in the superclass. ActiveRecord has_many declaration is an example.

Tuesday, January 19, 2016

Looking for Ruby Book Reviewers

I am looking for technical reviewers to review Essential Ruby Kindle book. I will mention your name and give a link to your site or blog  in the book. If you are interested, please contact me at bparanj at gmail dot com or RubyPlus contact form.

Tuesday, January 12, 2016

How to find out if a name is reserved in Rails 4.2.5

One of the articles that gets lot of traffic is : Reserved Words in Rails. If you do not use the generator to generate the code in your Rails project, you could potentially have class collision during runtime of your application. Here are the steps I followed:

1. I browsed the railties gem and searched for 'reserved by Ruby on Rails' to find where in the source code the check is done.
2. It is defined in the class rails/generators/base.rb in class_collisions(*class_names) protected method.
3. I went to the rails console to figure out how to use this method:

> require 'rails/generators/base'
NameError: uninitialized constant Rails::Generators::Actions
from /Users/bparanj/.rvm/gems/railties-4.2.5/lib/rails/generators/base.rb:17:in `'
pry(main)> require 'rails/generators/actions'
=> true
 pry(main)> require 'rails/generators/base'
=> true
 pry(main)> g = Rails::Generators::Base.new
=> # @_initializer=[[], {}, {}],
 @_invocations={},
 @after_bundle_callbacks=[],
 @args=[],
 @behavior=:invoke,
 @destination_stack=["/Volumes/Work/dev/ewok"],
 @in_group=nil,
 @options={},
 @shell=#, @mute=false, @padding=0>>
 pry(main)> g.send(:class_collisions, 'ActiveRecord')
Rails::Generators::Error: The name 'ActiveRecord' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.
pry(main)> g.send(:class_collisions, 'type')
=> ["type"]
pry(main)> g.send(:class_collisions, 'ActiveRecord', 'ActiveJob')
Rails::Generators::Error: The name 'ActiveRecord' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.



Methods Live in Class

$ irb
2.2.4 :001 > s = 'hi'
 => "hi"
2.2.4 :002 > s.methods
 => [:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, :%, :[], :[]=, :insert, :length, :size, :bytesize, :empty?, :=~, :match, :succ, :succ!, :next, :next!, :upto, :index, :rindex, :replace, :clear, :chr, :getbyte, :setbyte, :byteslice, :scrub, :scrub!, :freeze, :to_i, :to_f, :to_s, :to_str, :inspect, :dump, :upcase, :downcase, :capitalize, :swapcase, :upcase!, :downcase!, :capitalize!, :swapcase!, :hex, :oct, :split, :lines, :bytes, :chars, :codepoints, :reverse, :reverse!, :concat, :<<, :prepend, :crypt, :intern, :to_sym, :ord, :include?, :start_with?, :end_with?, :scan, :ljust, :rjust, :center, :sub, :gsub, :chop, :chomp, :strip, :lstrip, :rstrip, :sub!, :gsub!, :chop!, :chomp!, :strip!, :lstrip!, :rstrip!, :tr, :tr_s, :delete, :squeeze, :count, :tr!, :tr_s!, :delete!, :squeeze!, :each_line, :each_byte, :each_char, :each_codepoint, :sum, :slice, :slice!, :partition, :rpartition, :encoding, :force_encoding, :b, :valid_encoding?, :ascii_only?, :unpack, :encode, :encode!, :to_r, :to_c, :unicode_normalize, :unicode_normalize!, :unicode_normalized?, :>, :>=, :<, :<=, :between?, :nil?, :!~, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
2.2.4 :003 > s.instance_methods
NoMethodError: undefined method `instance_methods' for "hi":String
    from (irb):3
    from /Users/bparanj/.rvm/rubies/ruby-2.2.4/bin/irb:11:in `
'
2.2.4 :004 > String.instance_methods
 => [:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, :%, :[], :[]=, :insert, :length, :size, :bytesize, :empty?, :=~, :match, :succ, :succ!, :next, :next!, :upto, :index, :rindex, :replace, :clear, :chr, :getbyte, :setbyte, :byteslice, :scrub, :scrub!, :freeze, :to_i, :to_f, :to_s, :to_str, :inspect, :dump, :upcase, :downcase, :capitalize, :swapcase, :upcase!, :downcase!, :capitalize!, :swapcase!, :hex, :oct, :split, :lines, :bytes, :chars, :codepoints, :reverse, :reverse!, :concat, :<<, :prepend, :crypt, :intern, :to_sym, :ord, :include?, :start_with?, :end_with?, :scan, :ljust, :rjust, :center, :sub, :gsub, :chop, :chomp, :strip, :lstrip, :rstrip, :sub!, :gsub!, :chop!, :chomp!, :strip!, :lstrip!, :rstrip!, :tr, :tr_s, :delete, :squeeze, :count, :tr!, :tr_s!, :delete!, :squeeze!, :each_line, :each_byte, :each_char, :each_codepoint, :sum, :slice, :slice!, :partition, :rpartition, :encoding, :force_encoding, :b, :valid_encoding?, :ascii_only?, :unpack, :encode, :encode!, :to_r, :to_c, :unicode_normalize, :unicode_normalize!, :unicode_normalized?, :>, :>=, :<, :<=, :between?, :nil?, :!~, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]

Monday, January 11, 2016

Changing Self inside the Block

(1..10).tap {|x| puts "original: #{x.inspect}"}.tap {|x| puts "Original class: #{x.class}"}.to_a.tap {|x| puts "array: #{x.inspect}"}.tap {|x| puts "After class: #{x.class}"}

Wednesday, December 23, 2015

Test Rails 4.2.5 ActionMailer Settings

require 'action_mailer'

ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
   :address   => "smtp.gmail.com",
   :port      => 587,
   :domain    => "rubyplus.com",
   :authentication => :plain,
   :user_name      => "bparanj@rubyplus.com",
   :password       => "password",
   :enable_starttls_auto => true
  }
ActionMailer::Base.view_paths= File.dirname(__FILE__)

class Mailer < ActionMailer::Base

  def daily_email
    @var = "var"

    mail(   :to      => "bparanj@something.com",
            :from    => "bparanj@szy.com",
            :subject => "testing mail") do |format|
                format.text
                format.html
    end
  end
end

email = Mailer.daily_email.deliver_now
puts email
email.deliver

In mailer/daily_email.html.erb and mailer/daily_email.text.erb

this is an html email

and this is a variable <%= @var %>

this is a text email

and this is a variable <%= @var %>


Monday, December 21, 2015

How to include URL Helpers in Decorators in Rails 4.2.5

Add :
 
include Rails.application.routes.url_helpers
 
to the decorator. For example:
 
class BugsDecorator < ApplicationDecorator
  include Rails.application.routes.url_helpers
end 

Wednesday, December 16, 2015

ack options to list only file names

-w - Search whole word
-l  - Only print the filenames of matching files
-r - Recurse into subdirectories

ack -lrw '< MySuperClassName' --ignore-dir={app/assets,log,spec,vendor,public,coverage,config}

You can chain this to xargs to open all the matching file for editing like this:

ack -lrw '< MySuperClassName' --ignore-dir={app/assets,log,spec,vendor,public,coverage,config} | xargs mate


Sunday, December 13, 2015

Rails Performance Tools Presentation Notes

Tools for Linux

lsof
strace
ltrace

Tools for C Code

perftools
gdb

Tools for Networks

tcpdump
ngrep

Tools for CPU Usage

perftools
perftools.rb

Tools for Memory Usage

bleak_house
gdb.rb
memprof

LSOF

List open files

lsof -nPp

-n : Inhibits the conversion of network numbers to host names.
-P : Inhibits the conversion of port numbers to names for network files

TCP Dump

Dump traffic on a network

tcpdump -i eth0 -s 0 -nqA
tcp dst port 3306

Mammals

Mammals have hair or fur
Nurse their young with milk
have lungs and need air to breathe
Mammals that live on land have 4 legs and ears that stick out
Warm Blooded

Eg : Polar Bear, Gorilla, Horses etc

How to commit all deleted files in Git without affecting other modified files?

git ls-files --deleted | xargs git rm

Implementing Abs using Objects



def absolute(x)
  if x > 0
    x
  elsif x == 0
    0
  elsif x < 0
    -x
  end
end

# p absolute(0)


class GreaterThan
  attr_reader :number

  def initialize(value, number)
    @value, @number = value, number
  end

  def evaluate
    result[@number.send(:>, @value).class]
  end

  private

  def result
    {TrueClass => @number}
  end
end

# c = GreaterThan.new(0, -2)
#
# p c.evaluate

class LessThan
  attr_reader :number

  def initialize(value, number)
    @value, @number = value, number
  end

  def evaluate
    result[@number.send(:<, @value).class]
  end

  private

  def result
    {TrueClass => -@number}
  end
end


# c = LessThan.new(0, -2)
#
# p c.evaluate


class EqualTo
  attr_reader :number

  def initialize(value, number)
    @value, @number = value, number
  end

  def evaluate
    result[@number.send(:==, @value).class]
  end

  private

  def result
    {TrueClass => 0}
  end
end


# c = EqualTo.new(0, 0)
#
# p c.evaluate


def obzolute(x)
   [GreaterThan.new(0, x), LessThan.new(0, x), EqualTo.new(0,x)].each do |predicate|
      unless predicate.evaluate.nil?
        return predicate.evaluate
      end
   end
end

p obzolute(0)
p obzolute(-1)
p obzolute(2)


Second Version

class Predicate
  def initialize(operator, value)
    @operator, @value = operator, value
  end
 
  def evaluate
    @value.send(@operator.to_sym, 0)
  end
 
  def result
    {'>' => @value, '==' => 0, '<' => -@value}
  end
 
end

p1 = Predicate.new('<', -1)

p (p1.evaluate and p1.result['<'])


p2 = Predicate.new('==', 0)

p (p2.evaluate and p2.result['=='])


p3 = Predicate.new('>', 2)

p (p3.evaluate and p3.result['>'])

MIT Scheme Console

$ ./mit-scheme console
MIT/GNU Scheme running under OS X
Type `^C' (control-C) followed by `H' to obtain information about interrupts.

Copyright (C) 2014 Massachusetts Institute of Technology
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.

Image saved on Saturday May 17, 2014 at 2:39:25 AM
  Release 9.2 || Microcode 15.3 || Runtime 15.7 || SF 4.41 || LIAR/x86-64 4.118 || Edwin 3.116
;Warning: Invalid keyword: "console"
;Warning: Unhandled command line options: ("console")

1 ]=> 486

;Value: 486

1 ]=> (+ 137 349)

;Value: 486

1 ]=> (- 1000 334)

;Value: 666

1 ]=> (* 5 99)

;Value: 495

1 ]=> (/ 10 5)

;Value: 2

1 ]=> (+ 2.7 10)

;Value: 12.7

Combination = (operator operand1 operand2). The value of the combination is computed by applying the operator to the operands.

The prefix notation has the advantage of taking an arbitrary number of arguments. Making it easy to compute your tax deductions:

1 ]=> (+ 21 35 12 7)

;Value: 75

Calculate Mileage rate deduction:

1 ]=> (+ (* 57.5 200) (* 23 700))

;Value: 27600.

57.5 cents for each business mile driven and 23 cents for moving deduction. I drove 200 miles for business miles and 700 miles for moving. So I get a total deduction of $276 (since the answer is in cents).

This shows another advantage of prefix notation where we can have combinations of elements which are combinations.

Defining Variable

1 ]=> define size 2

;Syntactic keyword may not be used as an expression: #[keyword-value-item 13]
;To continue, call RESTART with an option number:
; (RESTART 1) => Return to read-eval-print level 1.

2 error> 
;Unbound variable: size
;To continue, call RESTART with an option number:
; (RESTART 4) => Specify a value to use instead of size.
; (RESTART 3) => Define size to a given value.
; (RESTART 2) => Return to read-eval-print level 2.
; (RESTART 1) => Return to read-eval-print level 1.

3 error> 
;Value: 2

3 error> (define size 2)

;Value: size

3 error> size

;Value: 2

3 error> (* 5 size)

;Value: 10

3 error> (define pi 3.14159)

;Value: pi

3 error> (define radius 10)

;Value: radius

3 error> (* pi (* radius radius))

;Value: 314.159

3 error> (define circumference (* 2 pi radius))

;Value: circumference

3 error> circumference

;Value: 62.8318

Installing Mit Scheme LISP on Mac OS 10.7.5

Hit this URL http://ftp.gnu.org/gnu/mit-scheme/stable.pkg/9.2/mit-scheme-9.2-x86-64.tar.gz on the browser to download the file.

 cd Downloads/
 cd mit-scheme-9.2
 cd src
 ./configure --prefix=/usr/local
 make -j9 compile-microcode
 make install
 cd /usr/local/bin
 ./mit-scheme --version

You should see:

MIT/GNU Scheme microcode 15.3
Copyright (C) 2014 Massachusetts Institute of Technology
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Image saved on Saturday May 17, 2014 at 2:39:25 AM
  Release 9.2 || Microcode 15.3 || Runtime 15.7 || SF 4.41 || LIAR/x86-64 4.118
  Edwin 3.116
Moriturus te saluto.

Saturday, December 12, 2015

Notes for 5 Hidden Gems of the Ruby Standard Library Presentation

Set
- It doesn't keep order
- It doesn't support duplicates
- It's very fast at finding elements


BLACKLISTED_IPS = %w(42.100.119.12 61.103.82.121)

def black_listed?(ip)
  BLACKLISTED_IPS.include?(ip)
end

vs

require 'set'

same code as before