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 %>
Wednesday, December 23, 2015
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
-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
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
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
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.
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
- 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
Find the process name using the process id
ps -p 1 -o comm=
/sbin/launchd
-p : PID
-o : command name
In this case the process id is 1 and comm is the command name. The story behind why I had to use this command. MySQL server stopped working on my Mac. It was complaining that the server process had quit without updating the PID file. The PID file did not exist. So I created one and put process id 1 as the value. When I made an attempt to restart the MySQL server, the entire machine rebooted. It turns out that the process with id one is the launchd that starts all other child processes in Mac.
/sbin/launchd
-p : PID
-o : command name
In this case the process id is 1 and comm is the command name. The story behind why I had to use this command. MySQL server stopped working on my Mac. It was complaining that the server process had quit without updating the PID file. The PID file did not exist. So I created one and put process id 1 as the value. When I made an attempt to restart the MySQL server, the entire machine rebooted. It turns out that the process with id one is the launchd that starts all other child processes in Mac.
Friday, December 11, 2015
Neither Pony nor ActionMailer appear to be loaded so email-spec is requiring ActionMailer.
Add require statement for action_mailer before email_spec in spec_helper.rb:
require 'action_mailer'
require "email_spec"
require 'action_mailer'
require "email_spec"
Tuesday, December 08, 2015
Find files that was changed before certain number of days
1. Find all controllers that was changed 4 days ago.
find ./app/controllers -type f -mtime -4
2. Find all views that was changed 4 days ago.
find . -mtime -4 -name "*.haml" -print
find ./app/controllers -type f -mtime -4
2. Find all views that was changed 4 days ago.
find . -mtime -4 -name "*.haml" -print
Monday, December 07, 2015
How to automatically source ~/.bash_profile in Mac OS
Add the line:
source ~/.bash_profile
to the ~/.bashrc file. Open a new terminal to test whether it works.
source ~/.bash_profile
to the ~/.bashrc file. Open a new terminal to test whether it works.
Sunday, December 06, 2015
Form vs Structure
Form: The visible shape of something Structure: The arrangement of and relations between the elements of something complex. Form relates to the external shape – best thought of as a silhouette. It is visible. Structure is goes beyond the visible – it is the internal development and relationship between parts. It is about the internal skeleton and organs. Think of it as an X ray or CT scan.
Friday, December 04, 2015
Find all files less than a certain size
find ./app/helpers -type f -size -50c | more
If you want to find files greater than a certain size
find ./app/helpers -type f -size+ 50c | more
If you want to find files greater than a certain size
find ./app/helpers -type f -size
Show All the Commits Behind the Master for a Given Branch in Git
This will prepend "git show" to the commit hash
git rev-list your-branch-name --not master | sed 's/^/git show /' | pbcopy
git rev-list rails424 --not master | sed 's/^/git show /' | xargs git show
will show the diff for each of the commit hash.
git rev-list your-branch-name --not master | sed 's/^/git show /' | pbcopy
git rev-list rails424 --not master | sed 's/^/git show /' | xargs git show
will show the diff for each of the commit hash.
Tuesday, December 01, 2015
How to check when a file was deleted in git
1. Check the log for a particular file.
git log -- app/views/articles/publish.html.erb
2. Copy the commit hash and do:
git show commit-hash
You can view the changes made to the files including the files that were deleted.
git log -- app/views/articles/publish.html.erb
2. Copy the commit hash and do:
git show commit-hash
You can view the changes made to the files including the files that were deleted.
Monday, November 30, 2015
Listing only deleted files between master and a given branch in git
git diff --name-status master..some-branch-name | sed '/^M/ d' | sed '/^A/ d' | mate
Sunday, November 29, 2015
Could not find 'railties' (>= 0) among 46 total gems
This happened in a Rails 5 alpha installation. Use:
bundle exec rails -v
bundle exec rails c
to resolve this issue.
bundle exec rails -v
bundle exec rails c
to resolve this issue.
Thursday, November 26, 2015
Rails 5 Quickly Book
I am updating my Rails 4.2 Quickly book to Rails 5. If you want to read it online, here are the links:
Chapter 1 : Running the Server
Chapter 2 : Hello Rails
Chapter 3 : Model
Chapter 4 : Model View Controller
Chapter 5 : View to Model
Chapter 6 : Update Article
Chapter 7 : Show Article
Chapter 8 : Delete Article
Chapter 9 : View Duplication
Chapter 10 : Relationships
Chapter 11 : Delete Comment
Chapter 12 : Restricting Operations
For initial setup, checkout this article : Creating a Rails 5 Project
Chapter 1 : Running the Server
Chapter 2 : Hello Rails
Chapter 3 : Model
Chapter 4 : Model View Controller
Chapter 5 : View to Model
Chapter 6 : Update Article
Chapter 7 : Show Article
Chapter 8 : Delete Article
Chapter 9 : View Duplication
Chapter 10 : Relationships
Chapter 11 : Delete Comment
Chapter 12 : Restricting Operations
For initial setup, checkout this article : Creating a Rails 5 Project
Tuesday, November 24, 2015
JSON::ParserError:
JSON::ParserError:
757: unexpected token at
Solution:
Escape the double quotes:
"{\"foo\":\"bar\"}"
757: unexpected token at
Solution:
Escape the double quotes:
"{\"foo\":\"bar\"}"
`class_exec': no block given (LocalJumpError)
This happens in Rspec if you miss the it() method. For example:
describe Car
expect(Car.speed).to eq(0)
end
The error message is not beginner friendly and can be improved.
describe Car
expect(Car.speed).to eq(0)
end
The error message is not beginner friendly and can be improved.
Friday, November 20, 2015
Thursday, November 19, 2015
Rename all .css.scss to .scss file
Stolen script to make upgrade to Rails 4.2 easier: Save it as .sh file, run chmod 755 renamer.sh
#! /usr/bin/env bash | |
for f in $(find . -type f -iname '*.css.scss'); do | |
renamed=$(echo "${f}" | sed 's/.css.scss$/.scss/g') | |
cmd="git mv ${f} ${renamed}" | |
echo $cmd | |
eval $cmd | |
done |
Monday, November 16, 2015
Wait for External calls to finish
Note to myself: Create an utility similar to this : https://robots.thoughtbot.com/automatically-wait-for-ajax-with-capybara to fix the sleep hack in Stripe project.
# spec/support/wait_for_external_call.rb
module WaitForExternalCall
def wait_for_remote_call
Timeout.timeout(Capybara.default_wait_time) do
loop until custom_assertion_passed?
end
end
def custom_assertion_passed?
end
end
RSpec.configure do |config|
config.include WaitForExternalCall, type: :feature
end
# spec/support/wait_for_external_call.rb
module WaitForExternalCall
def wait_for_remote_call
Timeout.timeout(Capybara.default_wait_time) do
loop until custom_assertion_passed?
end
end
def custom_assertion_passed?
end
end
RSpec.configure do |config|
config.include WaitForExternalCall, type: :feature
end
Sunday, November 15, 2015
Testing Tip
Instead of checking each attribute of a JSON response in your test, you can use json-schema for api validation. Use jsonschema.net to generate a valid JSON schema from a valid sample data. You can delete all the links that point to jsonschema.net and save the json file in the fixtures directory.
Could not find 'railties' (>= 0) among 46 total gem(s) (Gem::LoadError) in Rails 5 Project
Problem
zepho-mac-pro:rails5 zepho$ rails -v
/Users/zepho/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/dependency.rb:315:in `to_specs': Could not find 'railties' (>= 0) among 46 total gem(s) (Gem::LoadError)
Checked in 'GEM_PATH=/Users/zepho/.rvm/gems/ruby-2.2.3@r5blog:/Users/zepho/.rvm/gems/ruby-2.2.3@global', execute `gem env` for more information
from /Users/zepho/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/dependency.rb:324:in `to_spec'
from /Users/zepho/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_gem.rb:64:in `gem'
from /Users/zepho/.rvm/gems/ruby-2.2.3@r5blog/bin/rails:22:in `'
Fix:
zepho-mac-pro:rails5 zepho$ bundle check
Resolving dependencies...
The Gemfile's dependencies are satisfied
zepho-mac-pro:rails5 zepho$ gem list rails
*** LOCAL GEMS ***
jquery-rails (4.0.5)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.7)
rails-html-sanitizer (1.0.2)
sprockets-rails (2.3.3)
zepho-mac-pro:rails5 zepho$ gem list railties
*** LOCAL GEMS ***
zepho-mac-pro:rails5 zepho$ gem install rails
Fetching: rack-1.6.4.gem (100%)
Successfully installed rack-1.6.4
Fetching: activesupport-4.2.5.gem (100%)
Successfully installed activesupport-4.2.5
Fetching: actionview-4.2.5.gem (100%)
Successfully installed actionview-4.2.5
Fetching: actionpack-4.2.5.gem (100%)
Successfully installed actionpack-4.2.5
Fetching: railties-4.2.5.gem (100%)
Successfully installed railties-4.2.5
Fetching: activejob-4.2.5.gem (100%)
Successfully installed activejob-4.2.5
Fetching: actionmailer-4.2.5.gem (100%)
Successfully installed actionmailer-4.2.5
Fetching: arel-6.0.3.gem (100%)
Successfully installed arel-6.0.3
Fetching: activemodel-4.2.5.gem (100%)
Successfully installed activemodel-4.2.5
Fetching: activerecord-4.2.5.gem (100%)
Successfully installed activerecord-4.2.5
Fetching: rails-4.2.5.gem (100%)
Successfully installed rails-4.2.5
11 gems installed
zepho-mac-pro:rails5 zepho$ rails -v
Rails 5.0.0.alpha
zepho-mac-pro:rails5 zepho$ rails -v
/Users/zepho/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/dependency.rb:315:in `to_specs': Could not find 'railties' (>= 0) among 46 total gem(s) (Gem::LoadError)
Checked in 'GEM_PATH=/Users/zepho/.rvm/gems/ruby-2.2.3@r5blog:/Users/zepho/.rvm/gems/ruby-2.2.3@global', execute `gem env` for more information
from /Users/zepho/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/dependency.rb:324:in `to_spec'
from /Users/zepho/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_gem.rb:64:in `gem'
from /Users/zepho/.rvm/gems/ruby-2.2.3@r5blog/bin/rails:22:in `
Fix:
zepho-mac-pro:rails5 zepho$ bundle check
Resolving dependencies...
The Gemfile's dependencies are satisfied
zepho-mac-pro:rails5 zepho$ gem list rails
*** LOCAL GEMS ***
jquery-rails (4.0.5)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.7)
rails-html-sanitizer (1.0.2)
sprockets-rails (2.3.3)
zepho-mac-pro:rails5 zepho$ gem list railties
*** LOCAL GEMS ***
zepho-mac-pro:rails5 zepho$ gem install rails
Fetching: rack-1.6.4.gem (100%)
Successfully installed rack-1.6.4
Fetching: activesupport-4.2.5.gem (100%)
Successfully installed activesupport-4.2.5
Fetching: actionview-4.2.5.gem (100%)
Successfully installed actionview-4.2.5
Fetching: actionpack-4.2.5.gem (100%)
Successfully installed actionpack-4.2.5
Fetching: railties-4.2.5.gem (100%)
Successfully installed railties-4.2.5
Fetching: activejob-4.2.5.gem (100%)
Successfully installed activejob-4.2.5
Fetching: actionmailer-4.2.5.gem (100%)
Successfully installed actionmailer-4.2.5
Fetching: arel-6.0.3.gem (100%)
Successfully installed arel-6.0.3
Fetching: activemodel-4.2.5.gem (100%)
Successfully installed activemodel-4.2.5
Fetching: activerecord-4.2.5.gem (100%)
Successfully installed activerecord-4.2.5
Fetching: rails-4.2.5.gem (100%)
Successfully installed rails-4.2.5
11 gems installed
zepho-mac-pro:rails5 zepho$ rails -v
Rails 5.0.0.alpha
Creating a Rails 5 Project
1. Create a Gemfile
source "https://rubygems.org"
ruby '2.2.3'
gem 'rack', github: 'rack/rack'
gem 'rails', git: 'git://github.com/rails/rails.git'
gem 'arel', git: 'git://github.com/rails/arel.git'
2. bundle
3. bundle exec rails new . --dev --force
4. bundle exec rails s
Go to localhost:3000, you should now see 5.0.0.alpha in the environment.
Reference
Setting up Rails 5 app from edge
source "https://rubygems.org"
ruby '2.2.3'
gem 'rack', github: 'rack/rack'
gem 'rails', git: 'git://github.com/rails/rails.git'
gem 'arel', git: 'git://github.com/rails/arel.git'
2. bundle
3. bundle exec rails new . --dev --force
4. bundle exec rails s
Go to localhost:3000, you should now see 5.0.0.alpha in the environment.
Reference
Setting up Rails 5 app from edge
Monday, November 09, 2015
ActionController::UnknownHttpMethod:
In Rails 4.x:
In your tests, call process method like this:
process :some_action, 'OPTIONS'
In your tests, call process method like this:
process :some_action, 'OPTIONS'
Sunday, November 08, 2015
Redefining a Private Method in Ruby
class ActiveRecord
private
def hi
'I am private'
end
end
class ActiveRecord
def greet
hi
end
private
def hi
'I am redining you'
end
end
a = ActiveRecord.new
p a.greet
Monkey patching (Coding Horror):
class ActiveRecord
private
def hi
'I am private'
end
end
class MyActiveRecord < ActiveRecord
def greet
hi
end
private
def hi
'I am redefining you'
end
end
a = MyActiveRecord.new
p a.greet
Unnecessary Complication:
class Client
def print
say
end
private
def say
"hello"
end
end
# Create a subclass of Client
MyClient = Class.new(Client) do
define_method(:say) do
"hello from an overridden private method"
end
end
puts MyClient.superclass
my_client = MyClient.new
puts my_client.print
Simpler Way to Accomplish the Same Thing:
class Client
def print
say
end
private
def say
"hello"
end
end
class MyClient < Client
def say
"hello from an overridden private method"
end
end
puts MyClient.superclass
my_client = MyClient.new
puts my_client.print
private
def hi
'I am private'
end
end
class ActiveRecord
def greet
hi
end
private
def hi
'I am redining you'
end
end
a = ActiveRecord.new
p a.greet
Monkey patching (Coding Horror):
class ActiveRecord
private
def hi
'I am private'
end
end
class MyActiveRecord < ActiveRecord
def greet
hi
end
private
def hi
'I am redefining you'
end
end
a = MyActiveRecord.new
p a.greet
Unnecessary Complication:
class Client
def print
say
end
private
def say
"hello"
end
end
# Create a subclass of Client
MyClient = Class.new(Client) do
define_method(:say) do
"hello from an overridden private method"
end
end
puts MyClient.superclass
my_client = MyClient.new
puts my_client.print
Simpler Way to Accomplish the Same Thing:
class Client
def print
say
end
private
def say
"hello"
end
end
class MyClient < Client
def say
"hello from an overridden private method"
end
end
puts MyClient.superclass
my_client = MyClient.new
puts my_client.print
Thursday, November 05, 2015
Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true rails 4.2.4
In application.rb, inside the class add:
Rails.application.routes.default_url_options[:host] = "load url that is appropriate for different environments in your app here"
Now you can go to the rails console:
> include Rails.application.routes.url_helpers
and call different url_helpers like this:
profile_url
Rails.application.routes.default_url_options[:host] = "load url that is appropriate for different environments in your app here"
Now you can go to the rails console:
> include Rails.application.routes.url_helpers
and call different url_helpers like this:
profile_url
Monday, November 02, 2015
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
on Mac OS 10.10.5
Resolution:
bundle update json
Resolution:
bundle update json
The scope body needs to be callable.
Change :
scope :world_has_not_ended, where('end_time >= ?', Time.now)
to
scope :world_has_not_ended, -> { where('end_time >= ?', Time.now) }
scope :world_has_not_ended, where('end_time >= ?', Time.now)
to
scope :world_has_not_ended, -> { where('end_time >= ?', Time.now) }
Saturday, October 31, 2015
rr mocking framework
How to mock something and raise exception? In your model if you need to test something that's raises ActiveRecordNotFound, you can do :
stub(some_object).walk { raise }
Friday, October 30, 2015
Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources
bundle install --path vendor/cache
Wednesday, October 28, 2015
30-inch Apple Cinema HD Display vs 34" Class 21:9 UltraWide™ WQHD IPS Curved LED Monitor Dimensions
30-inch Apple Cinema HD Display
- Height: 21.3 inches (54.3 cm)
- Width: 27.2 inches (68.8 cm)
34-inch Class 21:9 UltraWide™ WQHD IPS Curved LED Monitor (34.0" Diagonal
Height: 33.7' inches
Width: 14.6 inches
Doing exact text search using ack
ack -w bugs
The -w flag will search only bugs and not bugs-bunny or anything other than exact match.
The -w flag will search only bugs and not bugs-bunny or anything other than exact match.
raise in Ruby
raise in Ruby will raise whatever exception you rescue in your code. So instead of doing :
raise MyException
you can just do:
raise
Here is a demo:
class MyException < Exception
end
class Foo
def hi
raise MyException.new('hello')
end
end
def tester
begin
f = Foo.new
f.hi
rescue
raise
end
end
tester
raise MyException
you can just do:
raise
Here is a demo:
class MyException < Exception
end
class Foo
def hi
raise MyException.new('hello')
end
end
def tester
begin
f = Foo.new
f.hi
rescue
raise
end
end
tester
Monday, October 26, 2015
Saturday, October 24, 2015
FactoryGirl::DuplicateDefinitionError: Factory already registered: author
I was getting this error in the rails console, when I did:
> FactoryGirl.find_definitions
Fix:
FactoryGirl.factories.clear
FactoryGirl.find_definitions
> FactoryGirl.find_definitions
Fix:
FactoryGirl.factories.clear
FactoryGirl.find_definitions
Thursday, October 22, 2015
Using Textmate to Browse Source Code using Bundler
Run:
export BUNDLER_EDITOR=mate
in the terminal. Now you can do:
bundle open gem-name
to view the source. You can also add the BUNDLER_EDITOR variable to the bash_profile.
export BUNDLER_EDITOR=mate
in the terminal. Now you can do:
bundle open gem-name
to view the source. You can also add the BUNDLER_EDITOR variable to the bash_profile.
Sunday, October 18, 2015
Tuesday, October 13, 2015
Notes from the book Team Geek
- Software development is a team sport.
- You need to work with other people.
- Share you vision.
- Divide the labor.
- Learn from others.
- Create a brilliant team.
Humility
- You are not the center of the universe.
- You don't know everything
- You are not incapable of making mistakes or being wrong
- It does not mean never failing
Respect
- Genuinely care about others you work with.
- You treat them as human beings
- You appreciate their abilities and accomplishments
Trust
- You believe others are competent and will do the right thing
- You're ok with letting them drive when appropriate
Almost every social conflict can be traced back to a lack of humility, respect or trust.
Lose the Ego
- Don't come off like a know-it-all
- Build a sense of team accomplishment and group pride
Learn to both deal out and handle criticism
- Learn to respect your peers and give constructive criticism politely
- Your self-worth shouldn't be connected to the code you write
Fail Fast, learn, iterate
- Failure is viewed as a golden opportunity to learn and improve
- Don't hide in the cave until it's perfect
- It's ok to show imperfect software to users and some trust that your users really do appreciate your efforts and are eager to see rapid improvements.
- Document your failures
What was learned and what is going to change as a result of the learning experience. Follow through on the proposed changes. Don't erase your tracks - light them up like a runway for those who follow you.
Postmortem should include:
• A brief summary
• A timeline of the event, from discovery through investigation to resolution
• The primary cause of the event
• Impact and damage assessment
• A set of action items to fix the problem immediately
• A set of action items to prevent the event from happening again
• Lessons learned
Leave Time for Learning
It's about increasing humility and being willing to learn as much as teach. Put yourself outside your comfort zone now and then.
Learn patience
Be open to influence
- It's ok for someone else to change your mind.
- Choose your battles carefully
- In order to be heard properly, you first need to listen to others
- Listening should take place before you've decided on something
Team Culture
Code reviews, TDD and the value you place on having good design docs before starting to crank out reams of code.Mission Statement is a way to describe the product goals and non goals.
Comments should be focused on why the code is doing what it's doing, not what the code is doing.
Require code reviews for every commit. Check for style, quality and mistakes.
Have real test and release processes. Testing should be part of the coding and review process.
Communication and process reduces the barrier to entry for newcomers.
Code is ultimately about communications with people.
An engineer needs nurturing, time and space to think and create.
Bad Manager
- Micromanagement
- Ignoring low performers
- Hiring pushovers : Your team won't be able to make a move without you. You can't take a vacation. You may feel secure in job.
Strive to hire people who are smarter than you and can replace you.
See failure as an opportunity to learn and not to point fingers or assign blame.
Do a postmortem of production failures. Document the events that led to the actual failure and develop a series of steps that will prevent it from happening in the future. Focus on the code of the problem and fix it once and for all.
Be a teacher and a mentor
- Experience with your team's processes and systems
- The ability to explain things to someone else
- The ability to gauge how much help your mentee needs
- Don't overexplain things
Set Clear Goals
Is there anything you need?You can increase intrinsic motivation by giving people three things: autonomy, mastery and purpose
Autonomy means no micromanagement. Mastery means giving the opportunity to learn new skills and improve existing skills
Code culture should include : Consensus based development, high-quality code, code reviews and an environment where people feel comfortable to try new things and to fail fast.
Protect your team's attention and focus. Don't let someone waste team's time.
Beware of those who are incapable of accepting a consensus decision, incapable of listening to or respecting other points of view and incapable of reaching compromises.
Redirect the energy of perfectionists
Keep track of your accomplishments and use them in your self-assessment
Three bullets and a call to action
Don't be all things. Define the problem narrowly and solve it well. Solve common problems for most users and do it really well. Focus on the user, not what's convenient for you to code. Complex things should feel seamless and easy.Ruby 2.2.3 Complex Basics
Ruby 2.2.3 Complex methods such as to_c, rationalize, rectangular, polar, +, -, /, *, real, imaginary and more. Click on the image below to watch the video.
Friday, October 09, 2015
Ruby 2.2.3 Bignum Basics
Ruby 2.2.3 Bignum methods such as remainder, fdiv, conversion to differnt base using to_s and bit_length. Click on the image below to watch the video.
Ruby 2.2.3 Comparable Basics
Ruby 2.2.3 Comparable methods such as <=> and between is covered in this video. Click on the image below to watch it.
Wednesday, October 07, 2015
Ruby 2.2.3 Binding Basics
Ruby 2.2.3 Binding basics such as binding, using binding with eval, local_variables, local_variable_set and local_variable_get. Click on the image below to watch the video.
Monday, October 05, 2015
Ruby 2.2.3 Enumerator Basics : Part 4
Ruby 2.2.3 Enumerator methods such as yield, feed, next_values, peek and peek_values. Click on the image below to watch the video.
Ruby 2.2.3 Enumerator Basics : Part 3
Ruby 2.2.3 Enumerator methods such as with_object and feed. Click on the image below to watch the video.
Sunday, October 04, 2015
Ruby 2.2.3 Enumerator Basics : Part 2
Ruby 2.2.3 Enumerator methods such as enum_for, to_enum and implementing Fibonacci sequence using Enumerator. Click on the image below to watch the video.
Ruby 2.2.3 Enumerator Basics : Part 1
Ruby 2.2.3 Enumerator methods such as each_with_object, next, next_values and feed. Click on the image below to watch the video.
Ruby 2.2.3 Module Basics : Part 9
Ruby 2.2.3 Module methods such as module_function, prepended, private_instance_methods, remove_method and undef_method. Click on the image below to watch the video.
Saturday, October 03, 2015
Ruby 2.2.3 Module Basics : Part 8
Ruby 2.2.3 Module methods such as extend_object, extended, included, method_added, remove_method and method_removed. Click on the image below to watch the video.
Ruby 2.2.3 Module Basics : Part 7
Ruby 2.2.3 Module methods such as remove_class_variable, singleton_class, alias_method and using instance_method in combination with define_method. Click on the image below to watch the video.
Ruby 2.2.3 Module Basics : Part 6
Ruby 2.2.3 Module methods such as private_class_method, private_instance_methods, private_method_defined?, protected_method_defined? and public_method_defined?. Click on the image below to watch the video.
Ruby 2.2.3 Module Basics : Part 5
Ruby 2.2.3 Module methods such as instance_methods, method_defined?, class_exec and module_eval. Click on the image below to watch the video.
Ruby 2.2.3 Module Basics : Part 4
Ruby 2.2.3 Module methods such as const_set, constants, include?, included_modules, instance_method. Click on the image below to watch the video.
Ruby 2.2.3 Module Basics : Part 3
Ruby 2.2.3 Module basics such as autoload, const_defined? and const_get. Click on the image below to view the video.
Ruby 2.2.3 Module Basics : Part 2
Ruby 2.2.3 Module methods such as autoload, autoload?, module_eval, class_exec, class_variable_defined?, class_variable_get, class_variable_set, class_variables and const_defined?
Friday, October 02, 2015
Ruby 2.2.3 Module Basics : Part 1
Ruby 2.2.3 Module methods such as constants, nesting, dynamically adding methods to a module, prepend and ancestors. Click the image below to watch the video.
Thursday, October 01, 2015
Revenue Scaling Problems with iPhone App Business
My first 10 iPhone apps made $30 / day consistently. If I project this, it will take 100 apps to make $300 / day ($9000 / month).
Problems
1. One app per week must be published (unrealistic for one-man company)
2. Cannot throw an app and expect sales without marketing effort.
3. I did not know the 'Equitable Revenue Share' rule during the start of the iPhone app business.
Only 2% of the iPhone apps make significant sales. The 98% of the apps do not make that much money.
Problems
1. One app per week must be published (unrealistic for one-man company)
2. Cannot throw an app and expect sales without marketing effort.
3. I did not know the 'Equitable Revenue Share' rule during the start of the iPhone app business.
Only 2% of the iPhone apps make significant sales. The 98% of the apps do not make that much money.
How to Increase iOS App Store Downloads
Free version with in-app purchases.
- Universal app for all devices.
- prweb.com : Press releases works (just breaks even for $5 product)
- Target Mac related sites for press releases.
Google Adwords
Wasted money on junk keywords. Use Double Click site to check traffic stats before spending on advertising on sites.
Be wary of people contacting you (harvesting email on your sales page) for ad placement on their site. These are lousy sites with no traffic.
- Universal app for all devices.
- prweb.com : Press releases works (just breaks even for $5 product)
- Target Mac related sites for press releases.
Google Adwords
Wasted money on junk keywords. Use Double Click site to check traffic stats before spending on advertising on sites.
Be wary of people contacting you (harvesting email on your sales page) for ad placement on their site. These are lousy sites with no traffic.
British Accent iPhone and iPad App
1. Content : High quality and unique, useful.
2. Price : Cheaper than alternatives.
3. Value : Better than alternatives.
Target Market
Call center employees. Foreign language speakers. Job seekers. Marketing to a new niche every time is more work.
Millions of users reading article on DailyMail website resulted in $1000 / day sales. This is not sustainable. Temporary spike is not useful in building business for long-term. Facebook, Twitter, News coverage etc.
Equitable revenue share : Refer Million Dollar Consulting.
2. Price : Cheaper than alternatives.
3. Value : Better than alternatives.
Target Market
Call center employees. Foreign language speakers. Job seekers. Marketing to a new niche every time is more work.
Millions of users reading article on DailyMail website resulted in $1000 / day sales. This is not sustainable. Temporary spike is not useful in building business for long-term. Facebook, Twitter, News coverage etc.
Equitable revenue share : Refer Million Dollar Consulting.
Seduction Flash Cards iPhone App
Quality content
- Existing brand. People search for 'Ross Jeffries'
Time Spent : 2 Hours
Money Spent : $50
Graphic Design : $50 (Elance)
Marketing : $0
ROI : Very High
Solves problem : Study cards anywhere
- Existing brand. People search for 'Ross Jeffries'
Time Spent : 2 Hours
Money Spent : $50
Graphic Design : $50 (Elance)
Marketing : $0
ROI : Very High
Solves problem : Study cards anywhere
Animal Hand Shadows iPhone App
Cost of Video Production : $1000
Sales = $0
YouTube Views = 0 (18 months after upload)
Solves a problem
No
Market
Unknown target market
Reach
None
Partnership
Unknown
Sales = $0
YouTube Views = 0 (18 months after upload)
Analysis
Solves a problem
No
Market
Unknown target market
Reach
None
Partnership
Unknown
Japanese Gestures iPhone App
Money Spent
Video production cost : $500
Noise reduction : $500
Solves a problem
I don't know
Target Market
Unknown
Competitors
None
Partners
Language companies?
Google search
Japanese gestures to check if any ads come up.
This is a big flop. 18 months after uploading to You-Tube, no one watched it.
Set clear expectations of how the work will be reviewed. Crappy videos could have been rejected and there would be no need to spend on noise reduction.
Market first approach would have made this idea non-viable.
Do not be carried away by the excitement of creating a product.
Video production cost : $500
Noise reduction : $500
Solves a problem
I don't know
Target Market
Unknown
Competitors
None
Partners
Language companies?
Google search
Japanese gestures to check if any ads come up.
This is a big flop. 18 months after uploading to You-Tube, no one watched it.
Lessons Learned
Top 500 Movies iPhone App
Development Time : 2 - 4 days
Graphic Design : $50
Marketing Effort : $0
Slowly moved up in sales. Solves problem : Track movies watched with fast lookup. High ROI, just below Seduction Flash Cards.
Graphic Design : $50
Marketing Effort : $0
Slowly moved up in sales. Solves problem : Track movies watched with fast lookup. High ROI, just below Seduction Flash Cards.
Science of Getting Rich iPhone App
Development Time : 2 to 4 hours
Content : Public Domain
Test : Will customers pay for convenience?
The answer is NO. This failed.
Content is not unique. Alternatives : Download from sites, iTune podcasts etc.
Content : Public Domain
Test : Will customers pay for convenience?
The answer is NO. This failed.
Content is not unique. Alternatives : Download from sites, iTune podcasts etc.
American Accent Made Easy iPhone App
Poor sales for Indian and Chinese versions. Ideally must be part of the generic product and optional in-app purchase. This increases download and it moves up on the chart.
Made the mistake of getting content from an accent reduction specialist who does not have the proper software / hardware to record quality audio. I wasted money on reducing the noise for a product that does not sell.
Made the mistake of getting content from an accent reduction specialist who does not have the proper software / hardware to record quality audio. I wasted money on reducing the noise for a product that does not sell.
iOxalate iPhone App
This was my first product on Appstore. No competitors. Solves a problem. Optimized for mobile context. Fast lookup of oxalate content on the go. Can be used for grocery shopping, eating out.
Reach : Difficult to reach target market. Very small market (intersection of iPhone owners and those who have suffered from kidney stones)
Partnership : Find kidney stones ebook seller and split revenues. Sales is almost 0 so there is no need to track and the partner can get a cut for every sale. Developing partnership with established medical companies is very difficult. Takes too much time and effort.
Development effort : 4 weeks. I was new to XCode tools. I had to go through the learning curve.
The aim was to go fast from code to cash. But it's easy to go fast from code to trash while time and money is wasted. Focus on reducing the waste when going from idea to code stage.
Reach : Difficult to reach target market. Very small market (intersection of iPhone owners and those who have suffered from kidney stones)
Partnership : Find kidney stones ebook seller and split revenues. Sales is almost 0 so there is no need to track and the partner can get a cut for every sale. Developing partnership with established medical companies is very difficult. Takes too much time and effort.
Development effort : 4 weeks. I was new to XCode tools. I had to go through the learning curve.
The aim was to go fast from code to cash. But it's easy to go fast from code to trash while time and money is wasted. Focus on reducing the waste when going from idea to code stage.
How to Write Application Statement for SaaS App
Identify the things about your application that you know with certainty, as well as things you don't yet know.
Write a rough story - two paragraphs or less. Be quick and to the point.
Seller is interested in selling ebooks. Each ebook can be uploaded to the site so that email stamping can be done after purchase. After purchase, fulfillment involves: email stamping the product and sending email with links to the downloadable ebook and any bonus ebooks. The links to the ebooks are limited by number of downloads and expires after a given time. Bounty window or cookie duration is 6 months and is not configurable. Publisher can provide multiple landing pages for a given product.
Affiliate marketer can login and view their bounties. Sellers can view their sales. The application provides transparency to publishers and marketers. Payment processing is out of scope of the product.
- What is notable about your application?
- What is it supposed to do?
- How will it support its users?
- Is it connected to a real-world example that you can study?
- Have you done something similar?
- What will make your design a success?
- What are the most challenging things to work out?
- What seems clear?
- What seems ill defined?
Design Story for Click Plan
This sales boosting application helps digital product sellers to promote and sell their products. One of the concerns is identifying all the actors and how the system is customized for each actor.- Can a seller be an affiliate or vice-versa?
- Do seller and affiliate have the same signup process?
- Do they have just one account?
Seller is interested in selling ebooks. Each ebook can be uploaded to the site so that email stamping can be done after purchase. After purchase, fulfillment involves: email stamping the product and sending email with links to the downloadable ebook and any bonus ebooks. The links to the ebooks are limited by number of downloads and expires after a given time. Bounty window or cookie duration is 6 months and is not configurable. Publisher can provide multiple landing pages for a given product.
Affiliate marketer can login and view their bounties. Sellers can view their sales. The application provides transparency to publishers and marketers. Payment processing is out of scope of the product.
Ruby 2.2.3 Class Basics : Part 2
Ruby 2.2.3 Class method inherited hook that allows to find out who subclassed a given class. Click the image below to watch the video.
Ruby 2.2.3 Class Basics : Part 1
Ruby 2.2.3 methods such as alias, creating class dynamically, superclass, allocate and new methods. Click the image below to view the video.
Monday, September 28, 2015
Ruby 2.2.3 Object Basics : Part 7
Ruby 2.2.3 Object Basics such as enum_for, to_enum, tainted? and taint. Click on the image below to watch the video.
Ruby 2.2.3 Object Basics : Part 6
Ruby 2.2.2 Object methods such as singleton_methods, tainted?, taint and tap is covered in this video. Click the image below to watch it.
Ruby 2.2.3 Object Basics : Part 5
Ruby 2.2.3 Object methods such as public_send, send, remove_instance_variable, respond_to?, singleton_class, and singleton_method. Click on the image below to view the video.
Sunday, September 27, 2015
Ruby 2.2.3 Object Basics : Part 4
Ruby 2.2.3 Object methods such as method, methods, nil?, freeze, object_id, protected_methods, public_methods and private_methods. Click the image below to watch the video.
Ruby 2.2.3 Object Basics : Part 3
Ruby 2.2.3 Object methods such as instance_variable_defined?, instance_variable_get, instance_variable_set, is_a?, kind_of?, itself and instance_variables. Click on the image below to watch the video.
Ruby 2.2.3 Object Basics : Part 2
Ruby 2.2.3 Object methods such as ==, equal?, eql?, extend, freeze, frozen?, instance_of? and inspect. Click on the image below to watch the video.
Ruby 2.2.3 Object Basics : Part 1
Ruby 2.2.3 Object basics such as available constants, data section, clone and define_singleton_method. Click on the image below to view the video.
Wednesday, September 23, 2015
Ruby 2.2.3 BasicObject Basics : Part 2
Ruby 2.2.3 BasicObject methods such as singleton_method_added, singleton_method_removed and singleton_method_undefined. Click on the image below to view the video.
Ruby 2.2.3 BasicObject Basics : Part 1
Ruby 2.2.3 basic methods such as ==, equal?, eql?, object_id, send, instance_eval and instance_exec. Click the image below to watch the video.
Sunday, September 20, 2015
Ruby 2.2.3 Symbol Basics : Part 2
Ruby 2.2.3 Symbol methods such as <=>, casecmp, empty?, intern, encoding, id2name, inspect, to_sym, length, slice, succ, swapcase and match . Click on the image below to watch the video.
Ruby 2.2.3 Symbol Basics : Part 1
Ruby 2.2.3 Symbol methods such as object_id, to_s, ==, <=>, to_s, [] and all_symbols. Click on the image below to watch the video.
Ruby 2.2.3 Hash Basics : Part 7
Ruby 2.2.3 Hash methods such as to_a, to_h, to_s, inspect, merge!, has_value?, values and values_at. Click the image below to view the video.
Ruby 2.2.3 Hash Basics : Part 6
Ruby 2.2.3 hash methods such rehash, reject, replace, select, shift and store. Click the image below to view the video.
Ruby 2.2.3 Hash Basics : Part 5
Ruby 2.2.3 Hash methods such as key, has_key?, delete, member?, merge and rassoc. Click the image below to view the video.
Ruby 2.2.3 Hash Basics : Part 4
Ruby 2.2.3 hash methods such as default proc, delete, delete_if, each and each_key. Click on the image below to watch the video.
Ruby 2.2.3 Hash Basics : Part 3
Ruby 2.2.3 hash methods such as assoc, key, any?, default and compare_by_identity?. Click on the image below to watch the video.
Ruby 2.2.3 Hash Basics : Part 2
Ruby 2.2.3 hash methods such as default, ==, upcase and try_convert. Click on the image below to view the video.
Ruby 2.2.3 Hash Basics : Part 1
Ruby 2.2.3 Hash methods such as default, comparison and access. Click on the image below to watch the video.
Saturday, September 19, 2015
Ruby 2.2.2 Array Basics : Part 12
Ruby 2.2.3 methods such as zip, values_at, unshift, uniq! and to_h. Click the image below to view the video.
Ruby 2.2.2 Array Basics : Part 11
Ruby 2.2.2 Array methods such as sort, take, take_while, uniq, transpose, to_h and transpose. Click the image below to watch the video.
Subscribe to:
Posts (Atom)