Sunday, September 20, 2015

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.

Ruby 2.2.2 Array Basics : Part 10

Ruby 2.2.2 Array methods such as repeated_permutation, replace, reverse, reverse_each, rindex, rotate, sample, select, shift and shuffle.

Ruby 2.2.2 Array Basics : Part 9

Ruby 2.2.2 Array methods such as pack, permutation, pop, product, push, rassoc, reject and repeated_combination. Click on the image to watch the video.

Friday, September 18, 2015

Ruby 2.2.2 Array Basics : Part 8

Ruby 2.2.2 Array methods such as frozen?, freeze, hash, include?, index, replace, insert, join, keep_if, last, collect, map and map with_index. Click on the image below to watch the video.

Ruby 2.2.2 Array Basics : Part 7

Ruby 2.2.2 Array methods such as drop_while, each_index, empty?, fetch, fill, index, first and flatten is covered. Click on the image below to watch the video.

Ruby 2.2.2 Array Basics : Part 6

Ruby 2.2.2 Ruby methods such as collect, map with index, map, combination, compact, concat, delete_at and delete_if. Click the image below to watch the video.





Problem Solving Techniques for Developers

Learn how to use :

1. Fish Bone Diagram
2. Why-Why Diagram and
3. How-How Diagram

to solving problems. Read the article here: Problem Solving Techniques for Developers





Ruby 2.2.2 Array Basics : Part 5

Ruby 2.2.2 Array methods such as any?, assoc, at, bsearch and clear. Click the image below to view the video.

Thursday, September 17, 2015

Ruby 2.2.2 Include and Extend Basics

Pre-requisites

 - Instance method and class method
 - included() hook method

Concepts Covered

1. Using Mixin to invoke an instance method in a module using include.
2. Using extend to to invoke a class method in a module
3. Using Plugin idiom to invoke instance and class methods in a module from a class.

Click the image below to watch the video.



Ruby 2.2.2 Array Basics : Part 4

Ruby 2.2.2 Array manipulations using &, *, +, -, <<, <=> and ==. Click the image below to watch the video.

Ruby 2.2.2 Array Basics : Part 3

Ruby 2.2.2 array methods such as equal?, try_convert and []. Click the image below to watch the video.

Ruby 2.2.2 Array Basics : Part 2

This video covers methods such as insert, pop, shift, delete_at, delete, compact, uniq, select, reject, drop_while, delete_if and keep_if. Click the image below to watch the video.

Wednesday, September 16, 2015

Ruby Interview Questions : Include vs Extend

How to implement extend with include?

  
  module Laughable
    def laugh
      p 'ha ha'
    end
  end

  class Clown
    class << self
      include Laughable
    end
  end

  Clown.laugh

  class Tiger
    extend Laughable
  end


  Tiger.laugh



Click the image below to watch the video.

Ruby 2.2.2 Array Basics : Part 1

Ruby 2.2.2 Array : push, unshift, include? and indexing. Click the image below to view the video.

Tuesday, September 15, 2015

Ruby Interview Question : Calculate Word Frequency

Two different solutions to calculating word frequency for a given text in Ruby. Click the image below to watch the video.

Monday, September 14, 2015

Ruby Interview Questions : Part 1

Logical and operator precedence, true and false boolean values and three different ways to call a method. Click on the image below to view the video.

Error installing mysql2 gem on Ubuntu

apt-get install libmysqlclient-dev

Error during json gem installation on Ubuntu 14

Error : /usr/bin/ld: cannot find -lgmp Solution: sudo apt-get install libgmp3-dev

Sunday, September 13, 2015

Ruby 2.2.3 String Basics : Ruby Silent Cast Part 13

Ruby 2.2.3 string methods ==, ===, chars, each_char, getbytes, setbytes, lines and next.

Friday, September 11, 2015

Ruby 2.2.3 String Basics : Ruby Silent Cast Part 12

Covers Ruby 2.2.3 tr_s, unpack, upcase, upto, force_encoding and valid_encoding? . Click the image below to view the video.

Ruby 2.2.3 String Basics : Ruby Silent Cast Part 11

Covers Ruby 2.2.3 to_r and tr . Click the image below to view the video.

Ruby 2.2.3 String Basics : Ruby Silent Cast Part 10

Covers Ruby 2.2.3 sum, swapcase, to_c and to_f. Click the image below to view the video.

Ruby 2.2.3 String Basics : Ruby Silent Cast Part 9

Covers Ruby 2.2.3 start_with?, strip and sub. Click the image below to view the video.

Ruby 2.2.3 String Basics : Ruby Silent Cast Part 8

Ruby 2.2.3 slice, split and squeeze. Click the image below to view the video.

Ruby 2.2.3 String Basics : Ruby Silent Cast part 7

Ruby 2.2.3 scan, scrub and indexing using regex. Click the image below to view the video.

Thursday, September 10, 2015

mysql2 gem error during Rails 4.2.4 upgrade

Error `rescue in spec': Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). (Gem::LoadError) Solution Add the following version of mysql2 gem to Gemfile. gem 'mysql2', '~> 0.3.18' run bundle.

Ruby String Basics Silent Cast : Part 6

Ruby 2.2.3 string basics such as oct, ord, partition, prepend, replace, reverse, rindex, rjust, rpartition and rstrip. Click the image below to watch the video.

Ruby String Basics Silent Cast : Part 5

Click on the image below to play the silent cast.
This episode covers Ruby 2.2.3 basics such as converting string to symbols, symbol comparison, ljust, lstrip, regular expression match and succ.

Object Reuse vs Component Reuse

In the 1992 book 'Object Oriented Software Engineering: A Use Case Driven Approach' Ivar Jacobson talks about three types of objects and one of the types he talks about is Entity. Let's say we have a product, the intention is to reuse this object in different applications such as Order Entry, Fulfillment, Inventory Management, Catalog etc.

There are several problems with this object reuse:

1. The object becomes big.
2. Only some methods are used in some applications.

 From the perspective of the developer of that
object, it is difficult to figure out which applications will be affected when a certain method changes. It is easier to reuse if a group of objects provides a service that is focused on doing one thing really well. In this approach you may end up with different components that have the product object, but they will be small since they are focused on doing only one thing. We can namespace the product so that there will be no conflicts in applications that use them.

Ruby String Basics : Part 4

Click the image below to watch the Ruby SilentCast and learn Ruby 2.2.3 String methods : empty?, size, gsub, ord, hex, include?, index, replace, insert and inspect.

Tuesday, September 08, 2015

Ruby String Basics : Part 3

Ruby 2.2.3 methods char, clear, concat, count, crypt, delete, downcase, dump, each_byte, each_char, each_codpoint and each_line.

Ruby 2.2.3 String Basics : Part 2

Ruby 2.2.3 String basics that covers force_encoding, bytesize, byteslice, capitalize, casecmp, center, chomp and chop.

Ruby String Basics : Ruby Silent Cast

This lesson covers the String API such as try_convert, string interpolation, concatenation, hat operator and more.

Ruby String Basics : Part 1

Click the image below to watch the video.

Monday, September 07, 2015

Sunday, September 06, 2015

Rails 4.2 Tutorial for Beginners

This is the first lesson in Rails 4.2 Quickly course. This will help you setup your initial project and check your development environment.

(3 minutes)

Ruby Silent Casts

Why silent?

What's in it for you?

- Your brain has to fill in the blanks
- You will be able to connect the dots and develop the understanding yourself
- No one likes to read documentation. These videos will be live coding with no reading.
- You can listen to something else while you watch the videos
- Easy to brush up basics before the interview
- Free to watch on browser and reasonable price for download option

What's in it for me?

- Less time for me to produce the video
- I can convert a byproduct of my interview preparation and practice to money
- I can use the time saved in audio recording and editing in creating more content
- Release something imperfect and improve on it over time based on demand

Thursday, September 03, 2015

Using Graph of Objects as the Unit of Reuse

Composition


I was refactoring code from an old project. It had used lot of stubs and mocks. The resulting design was not reviewed after taking a break from coding. But the methods that use the same variables were grouped together. This could also be due to the fact that I was coding alone. TDD and Pair-Programming go together. So when I revisited the code after a few months break, I was able to look at it from a fresh new perspective.

By rewriting code from scratch, while developing the gem, you are forced to think about the user of the library when you have to write the README, gem summary and description in the gem spec file. This  forces you to think about the functionality of the gem and how it can be used from a user’s perspective. Coming up with a concise description of the gem also defines how focused it should be, this helps in developing a cohesive gem.

By using structs instead of stubs and mocks, the code became more cohesive. During the rewriting process, I constantly asked myself :

“How likely is this going to change if Rails changes?”. 

I decided to keep dependencies such as product_id, product_name and anything that did not call ActiveRecord methods as safe bets because I can define methods with the same name on those objects.

Making the objects cohesive was a conscious choice, I asked myself :

“Is this data operating on this object all the time?”. 

If not, I split them so that they did operate with the object all the time.

The private methods were moved to small highly cohesive classes that can be composed to accomplish higher level tasks. The Micro Gem packages a group of objects that collaborate to accomplish one task that is done very well. The objective is not to reuse objects in different contexts but to isolate dependencies and provide a specific service to a developer. It encapsulates the knowledge required to implement something and makes it easy for other developers to utilize the service provided by the group of objects collaborating together.

Developing a quality product is challenging. There is no silver bullet. There is no one right way to do it. It’s like a stereo dial, you have to try different approaches and learn what combination works best for you. It could be top-down, bottom-up or combination of top and bottom up approaches with, some upfront design, TDD, PPP etc.

Took related private methods and moved them into a small classes with well defined interface that encapsulates the knowledge about accessing the external data structure, Paypal in this case.

About Not Aiming for Object Reuse


By focusing on a group of objects that provide one service, we avoid the following questions that can lead to confusion about the code base.
  1. Who are the clients of this class?
  2. What is the impact of changing the class?
  3. Which use cases need this class?
Confusion is the enemy of clarity and leads to difficulty in maintenance. Using a graph of objects that has single well defined purpose is a better unit of reuse in the long term for ease of maintenance.

Data Dictionary - Do you really need it?

A data dictionary is a database that describes all the significant data in a project. On large projects, a data dictionary is also useful for keeping track of huge amount of class definitions. On large team projects, it’s useful for avoiding naming clashes. A clash might be a direct, syntactic clash, in which the same name is used twice, or it might be a more subtle clash (or gap) in which different names are used to mean the same thing or the same name is used to mean subtly different things. For each class, the data dictionary contains the item’s name and description. The dictionary might also contain notes about how the item is used.

-- Steve McConnell (Code Complete 2)

How practical is creating and maintaining data dictionary? In a big company, it's difficult to agree upon a common name. So I think this is not practical. Good news is data dictionary is not required if you create Micro Gems. Since it provides a namespace for the classes that collaborate to provide a cohesive unit of functionality.  You could have many gems with the same class name but has different methods to capture different abstractions.

Wednesday, September 02, 2015

Colt Gem Ruby Critic Analysis

You can see all the classes gets a 'A' rating.

Here is the Churn vs Complexity Chart

The only code smell is the long parameter list. This cannot be avoided because all the parameters are needed to make the Stripe API call. We have an option of creating a value object to provide the needed values but it complicates the client code where you need to create an instance of the value object and unpacking it in the implementation. This is a conscious design choice and is not based on ignorance.





Top Down Vertical Slice Risk Oriented Integration

How can you avoid developing a brittle Rails app?


Submarine Pattern in Rails


1. Write a small Rails app for one function.
2. Get it working.
3. Extract the re-usable code from the Rails app into a Micro Gem.
4. Make sure the dependency direction is from the Rails app to the Micro Gem. If you have dependency that goes in the other direction to the Rails framework, you will have headaches during Rails upgrade. It will defeat the purpose, because you will end up with Spagetti code.
5. Refactor the Rails app to use the Micro gem.

Repeat the process for flushing out the details of other features. Only the features with high risk are split into a small Rails app for each of the high risk feature. The main Rails app uses the Micro Gems to delegate the tasks.

In my project, I have extracted dependencies that are due to third-party API such as:

1. Amazon S3
2. Paypal Express Checkout
3. Stripe Subscription API

to mention a few.  These are not just risky parts of the system, they also have their own release schedule. We don't want to rely on a third party release schedule. We can upgrade the Micro Gems as per our schedule and use the newer version of our gems in the project. We also contain any problems that may arise by isolating them into it's own Micro Gem that provides a useful functionality. I also don't need the flexibility of switching one of these third party API with their alternatives.

I have also extracted gems for functionality that is run as the background jobs when some event happens in the Rails app.

Reference


Code Complete 2 by Steve McConnell

Monday, August 31, 2015

Element not found in the cache - perhaps the page has changed since it was looked up

The workaround is to add a sleep call for 3 seconds. Let me know if there is a better solution.

WARNING: VCR::RSpec::Macros is deprecated. Use RSpec metadata options instead `:vcr => vcr_options`

Change this:

RSpec.configure do |config|
  config.extend VCR::RSpec::Macros #deprecated
end

to :

VCR.configure do |config|
  config.configure_rspec_metadata!
end

Saturday, August 29, 2015

Fail Early and Loudly

One of the things I learned the hard way is that a software should fail loudly. If you fail silently, it becomes very difficult to find the cause of the problem and fix it quickly. Raise exception as close as possible to the failure so that we can quickly figure out the issue. The exception should contain all the relevant data, the location and the likely cause of failure.

The concept of failing loudly is discussed in the Code Complete 2 book by Steve McConnell. If you just read the theory, you need to expose yourself to that theory repeatedly so that you will be able to apply it in practice. If you learn by experience it becomes easier to grasp that theory quickly and you will never forget it.

Example 1:

One of the gems that I developed requires Ruby 2.2.2 or above. When I did:

$ gem install merlot
Fetching: posix-spawn-0.3.11.gem (100%)
Building native extensions.  This could take a while...
Successfully installed posix-spawn-0.3.11
Fetching: pdf-core-0.6.0.gem (100%)
Successfully installed pdf-core-0.6.0
Fetching: ttfunk-1.4.0.gem (100%)
Successfully installed ttfunk-1.4.0
Fetching: prawn-2.0.2.gem (100%)
Successfully installed prawn-2.0.2
Fetching: merlot-0.1.0.gem (100%)t.1.0.gem
ERROR:  Error installing merlot:
merlot requires Ruby version >= 2.2.2.

Boom! The command fails at the very last step. It does not fail early. The precondition must be checked before wasting time by installing all the dependent gems.

Example 2 :

I turned off my WiFi and did:

$ gem install bacardi
ERROR:  Could not find a valid gem 'bacardi' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - no such name (https://rubygems.org/specs.4.8.gz)

The error message I receive has no indication on how the user can recover from this problem. Ideally, we want our software to check for the precondition to be satisfied. In this case, a valid Internet connection. This also happens when I am at Starbucks and I have connected to the WiFi but I have not agreed to the terms and conditions. Wouldn't it be better to catch this particular exception and provide a clear message to the user like:

'We have detected a problem with your Internet connection. Please check your connection and try again.'.

The software we develop following this principle would be user friendly and robust under abnormal conditions.

Example 3 :

I worked on a Rails project where one of the gems in the Gemfile used a private gem repository on github. The Gemfile used :github to specify the private gem location, when I ran bundle install, I got the error:

Fetching gem metadata from https://rubygems.org/.Retrying dependency api due to error (2/4): Bundler::HTTPError Network error while fetching 

https://bundler.rubygems.org/api/v1/dependencies?gems=rack-netscaler,rack-timeout,sprockets-rails,rails,rainbow,rdoc,ref,rspec-support,rspec-expectations,rspec-collection_matchers,rspec-core,rspec-example_steps,rspec-mocks,rspec-rails,ruby-progressbar,rubocop,rubyzip,sass-rails,sdoc,websocket,selenium-webdriver,simplecov-html,simplecov,spring,therubyracer,typhoeus,uglifier,vcr,vcr-helper,web-console,webmock

The actual error message has nothing to do with the cause. It turns out that I did not have access to that repository and the admin had to add me as one of the contributor to that repository. Wouldn't it be nice, if either the Bundler or the Github API provided a clear message stating the cause and how to fix it by providing a link for reference? 

Saturday, August 22, 2015

Paypal Express Checkout Error

Problem :

Security header is not valid", "ErrorCode"=>"10002"

Solution:

This error is shown when you are not properly logged into the sandbox account on paypal's site.

0. Login to www.paypal.com
1. Go to https://developer.paypal.com/developer/accounts
2. Copy API credentials for a sandox user with Business-Pro account.

1. Login to sandbox.paypal.com
2. Got to your site and checkout
3. When sent to paypal, login as one of your buyer test accounts

Resources

1. Bogus gateway to test PayPal
https://github.com/sideshowcoder/active_merchant/blob/192f49762172dc41450d7a3605158d45eb55b83b/lib/active_merchant/billing/gateways/paypal_bogus.rb
2. Classic API Endpoints
https://developer.paypal.com/webapps/developer/docs/classic/api/endpoints/
3. Merchant SDK Ruby
https://github.com/paypal/merchant-sdk-ruby
4. How to create and process an order using Express Checkout
https://developer.paypal.com/docs/classic/express-checkout/ht_ec-orderAuthPayment-curl-etc/
5. Sample Webapp that generates SDK code to use
https://paypal-sdk-samples.herokuapp.com/merchant/get_express_checkout_details

Thursday, August 20, 2015

missing files in gem after gem build

Bundler works in a weird way. The files that are not checked in to git will not get included. You have to add all the files to the git and then run gem build. You can verify it has included all the files by running gem unpack and opening the unpacked directory to verify the new files.

Thursday, August 13, 2015

Using RSpec with Ruby Gem

You can generate the required files when you create the directory structure for a gem by doing :

bundler gem --test=rspec my_gem

If you have already created the gem skeleton, it uses Minitest by default. You can make the following changes to switch to rspec:

1. Add :

spec.add_development_dependency "rspec"

to .gemspec file. Run bundle install.

2. Create Rakefile in the root of the gem:

require "bundler/gem_tasks"
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec)

task :default => :spec

3. Create spec/spec_helper.rb:

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'your-gem'

4. Create spec/yukon_spec.rb:

require 'spec_helper'

describe 'Your Gem' do
  it 'has a version number' do
    expect(YourGem::VERSION).not_to be nil
  end

  it 'does something useful' do
    expect(false).to eq(true)
  end
end

5. Run it:

rspec spec/yukon_spec.rb --color --format doc

Tuesday, August 11, 2015

Problem during RVM installation on Mac OS

Problem :

gpg: no valid OpenPGP data found.

Solution :

gpg --keyserver hkp://keys.gnupg.net:80 --recv-keys D39DC0E3

to force it to talk port 8

Saturday, July 25, 2015

Docker Q&A

1. How to monitor the processes?

Process monitoring builtin.

2. Logging and log files.

Stdin and Stdout. Can be forwarded. Syslog and journald driver.

3. Storing and manipulating files.

Create volume.
docker run -v /foo

docker run -v /var/foo:foo

4. Do we need to rebuild the image if the code is changed?

See Docker Rails Dev Demo

5. Why set :bind, '0.0.0.0' ? It does not work without this line.

6. How to run tests when the image is built?

  Dockerfile is not used to run unit tests.

Friday, July 24, 2015

Notes from How to Debug Anything Presentation by James Golick

A blind debugging session.
The website using PHP is down.
What we have to work with

The source code. (No)
Knowledge of the system. (No)
Familiarity with the programming language. (No)
SSH Access. (Yes)

Logging in the real world is often useless.
Find a pid. ps aux | grep apache

sudo strace -ff -s 2048 -p pid

How to read strace output

write(l, "hi\n", 3) = 3

write -> function name
arguments are l, "hi\n" and 3
return value is 3

To learn more about system calls: man 2 write

strace gives lot of output. Work backwards and find the failure. Look for the error message in the strace output. Find the cause by reading the strace output. Find the offender and write down your hypothesis. Prove your hypothesis. Find the offender. Fix the bug.

0. Forget everything you think you know.
1. Get a third party opinion.
2. Refer the 'Linux Performance Tools' diagram for a list of third-party tools.

You can also use strace to start a process.

sudo strace -ff apt-get update

Work backwards, find failure. Find the cause. Confirm your hypothesis. Locate a hook. Stare at the code. Confirm your hypothesis.

2. Locate the correct source code.
3. Identify a hard-coded string to grep for.
4. Stare at the code until it makes sense.
5. Fix whatever is broken.


0. Forget everything you think you know.
1. Get a third party opinion.
2. Locate the correct source code.
3. Identify a hard-coded string to grep for.
4. Stare at the code until it makes sense.
5. Fix whatever is broken.

puts Process.ppid

t = Thread.new do
   sleep 10
end

# Grabbing the pid.
pid = Process.pid

puts pid

# Get the child pids.
pipe = IO.popen("ps -ef | grep #{pid}")

child_pids = pipe.readlines.map do |line|
  puts line
  parts = line.split(/\s+/)
  # puts parts
  # parts[2] if parts[3] == pid.to_s and parts[2] != pipe.pid.to_s
end.compact

# Show the child processes.
# puts child_pids
#
#
# q = Queue.new
# # q.pop
#
t.join

Thursday, July 02, 2015

Colt Gem Released

Colt is a micro gem used to subscribe to a given plan using the Stripe API. The plans must already exist in your account. The current version can check Stripe credentials and Stripe API version.

 Source Code. You can find the different versions at Rubygems.org

Tuesday, June 30, 2015

Check Amazon S3 Credentials

1. gem install aws-s3
2. In IRB console : require 'aws/s3'
3.
AWS::S3::Base.establish_connection!(access_key_id: 'abcd', secret_access_key: 'secret')
AWS::S3::Service.buckets
AWS::S3::Bucket.find('your-existing-bucket-name')

It would be nice to steal code from aws-s3 gem to test if the credentials is valid or not.

ERROR: "https://rubygems.org" is not allowed by the gemspec, which only allows "TODO: Set to 'http://mygemserver.com'"

Problem: 

Not able to publish gem to rubygems.org

Resolution:

Delete the following lines from your-gem.gemspec file.

  if spec.respond_to?(:metadata)
    spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
  else
    raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
  end

how to use active support outside of rails

Error : NoMethodError: undefined method `hours' for 1:Fixnum

Resolution:

1. bundle open activesupport
2. Search for 'def hours', it is found in core_ext/numeric/time.rb
3. Add require 'active_support/core_ext/numberic/time.rb'

This is better than doing : require 'active_support/all'

Saturday, June 27, 2015

How to use Simplecov in gem development

1. Add the simplecov gem and start before anything else in test_helper.rb

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'simplecov'

SimpleCov.start

require 'rasam'
require 'minitest/autorun'

2. You can mark private methods as:
    # :nocov:
  to exclude from test coverage.
 
3. Run : rake test

4. Open coverage/index.html

Friday, June 26, 2015

How I resolved confusing tests and production code


Pair Ranking is very well defined problem solving technique. When my code become convoluted I had to switch my perspective to that of the user to improve the code and the tests. Read more about it here: TDD Beyond Basics : Outside In Perspective. This also shows you an example of how you could use this gem.

Searching for a given element in an array of arrays in Ruby

How to pull the number 3 from this list by searching for the value 'c'.

records =
[
 ["a","1"],
 ["b","2"],
 ["c","3"]
]

search_for = 'c'

Solution 1:

test = records.select{ |x| x[0] == search_for }

p test[0][1]

Solution 2:

p records.assoc(search_for).last

Playing with Rails 4.2.3

zepho-mac-pro:blog zepho$ rails g scaffold article title
      invoke  active_record
      create    db/migrate/20150626235457_create_articles.rb
      create    app/models/article.rb

  BLAH, BLAH, BLAH

zepho-mac-pro:blog zepho$ rake db:migrate
== 20150626235457 CreateArticles: migrating ===================================
-- create_table(:articles)
   -> 0.0015s
== 20150626235457 CreateArticles: migrated (0.0016s) ==========================

zepho-mac-pro:blog zepho$ rails c
Loading development environment (Rails 4.2.3)
2.2.2 :001 > Article
 => Article (call 'Article.connection' to establish a connection)
2.2.2 :002 > Article.count
   (0.1ms)  SELECT COUNT(*) FROM "articles"
 => 0

Thursday, June 25, 2015

Pair Ranking Algorithm

require 'highline/import'
require "pp"
require 'rasam'

include Rasam

options = ask("Enter your choices (or a blank line to quit):",
lambda { |ans| ans =~ /^-?\d+$/ ? Integer(ans) : ans} ) do |q|
  q.gather = ""
end

@pr = PairRank.new(options)
@saved_combinations = Array.new(@pr.combinations)
combinations = Array.new(@pr.combinations)

pair = combinations.shift

def get_user_choice_for(pair)
  choose do |menu|
    menu.prompt = "Please choose your favorite: "

    pair.each do |c|
      menu.choice(c) do
        say(c)

        rationale = ask("Why?  ")

        say(rationale)

        rc = RationalChoice.new(pair, c, rationale)
        @pr.make(rc)
      end
    end
  end
end

loop do
  p pair  
  get_user_choice_for(pair)
  break if combinations.empty?
  pair = combinations.shift
end


@pr.decisions.each do |d|
  p d.to_s
end


p @pr.score_for('A')
p @pr.score_for('B')
p @pr.score_for('C')

def handle_ties(pair)
  choose do |menu|
    menu.prompt = "Please choose your favorite: "

    pair.each do |c|
      menu.choice(c) do
        say(c)

        rationale = ask("Why?  ")

        say(rationale)

        rc = RationalChoice.new(pair, c, rationale)
        @pr.make(rc)
      end
    end
  end
end

loop do
  p 'Handling a tie'
  if @pr.tied_pair.empty?
    break
  else
    handle_ties(@pr.tied_pair)
   
    @pr.decisions.each do |d|
      p d.to_s
    end
   
    p @pr.score_for('A')
    p @pr.score_for('B')
    p @pr.score_for('C')
    p @pr.tied_pair
   
  end
end

find numbers that are same in an array ruby

a = [0,1,2,2,3,3]
x = a.find_all { |e| a.count(e) > 1 }
   
p x

Wednesday, June 24, 2015

Pair Ranking Gem Released

Select a single winner using votes that express preferences. This can also be used to create a sorted list of winners. rasam gem

Create Gem and Publish to Rubygems

$gem build rasam.gemspec
$gem push rasam-0.1.0.gem

Generate all combinations of a given length for a list of items

In Ruby 2.2.2:

 a = [1,2,3,4]
 a.combination(2)
 => # 

We need to call to_a on this enumerator:

 a = ['A', 'B', 'C', 'D']
 => ["A", "B", "C", "D"]
> a.combination(2).to_a
 => [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]

How to provide a default value for all elements in a hash

a = Hash.new(0)
 => {}
> a['x']
 => 0

`require': cannot load such file -- minitest/autorun

Install Minitest gem by running: bundle install

Eliminate spaces, -, +, *, /, = and parentheses in a string

Run:

str = "Revenue - Costs * (1 + Profitpercentage)"
p str.scan(/[A-Za-z]+/)

at http://rubyplus.biz/

You will see:

["Revenue", "Costs", "Profitpercentage"]

How to delete nested hash elements based on the elements properties

data = {
"total_records"=>3,
"records"=>
   [{"title"=>"Val1",
   "coins"=>1},
   {"title"=>"Val2",
   "coins"=>1},
   {"title"=>"Val3",
   "coins"=>1}]
}

p data

data['records'].delete_if{ |h| %w(Val1 Val2).include?(h['title']) }

p data

Output:

{"total_records"=>3, "records"=>[{"title"=>"Val1", "coins"=>1}, {"title"=>"Val2", "coins"=>1}, {"title"=>"Val3", "coins"=>1}]}
{"total_records"=>3, "records"=>[{"title"=>"Val3", "coins"=>1}]}

Two HERE Docs in Ruby 2.2.2

data = [
<<'EOT1', <<'EOT2'
more text
EOT1
and more
EOT2
]

p data

An error occurred while installing json (1.6.1), and Bundler cannot continue.

Make sure that `gem install json -v '1.6.1'` succeeds before bundling.
zepho-mac-pro:dynamic-menus zepho$ gem install json -v 1.6.1
Building native extensions.  This could take a while...
ERROR:  Error installing json:
ERROR: Failed to build gem native extension.

    /Users/zepho/.rvm/rubies/ruby-2.2.2/bin/ruby -r ./siteconf20150624-48402-1w7o7yz.rb extconf.rb
checking for ruby/re.h... yes
checking for ruby/encoding.h... yes
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling generator.c
generator.c:952:47: error: too few arguments provided to function-like macro invocation
    VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                              ^
generator.c:952:11: warning: incompatible pointer to integer conversion initializing 'VALUE' (aka 'unsigned long') with an expression of type 'VALUE (const char *, long)';
    VALUE result = rb_str_new(FBUFFER_PAIR(fb));
          ^        ~~~~~~~~~~
1 warning and 1 error generated.
make: *** [generator.o] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/zepho/.rvm/gems/ruby-2.2.2@dmenu/gems/json-1.6.1 for inspection.
Results logged to /Users/zepho/.rvm/gems/ruby-2.2.2@dmenu/extensions/x86_64-darwin-11/2.2.0/json-1.6.1/gem_make.out


Resolution: Downgrade ruby from 2.2.2 to 2.1

Could not find coffee-script-source-1.1.3 in any of the sources

Resolution:

bundle update --source coffee-script-source

Top 6 Ruby Links for June 24, 2015


1. How to build a rails 5 api only and backbone application

2. Provisioning a Server for Rails Stack using Sunzi Gem

3. How to Setup Vagrant for Rails Development

4. Using the Rails 5 Attributes API Today, in Rails 4.2

5. Render Markdown views with Redcarpet and Pygment in Rails

6. Subscribing for events in rails_event_store

Tuesday, June 23, 2015

How to check postgres version

There are two ways:

#1:
sudo -u postgres psql
psql (9.4.4)
Type "help" for help.

postgres=# \q

#2.
deploy@localhost:~/apps/your-app/current$ psql --version

psql (PostgreSQL) 9.4.4

rbenv: version `ruby' is not installed on production


1. env | grep PATH

Check that rbenv shims is in the path:

PATH=/usr/local/rbenv/shims:/usr/local/rbenv/shims:/usr/local/rbenv/bin:/usr/local/rbenv/shims:/usr/local/rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript

2.

See `rbenv help ' for information on a specific command.
For full documentation, see: https://github.com/sstephenson/rbenv#readme
deploy@localhost:~/apps/carmel_production/current$ rbenv versions
rbenv: version `ruby' is not installed
  2.2.2
deploy@localhost:~/apps/carmel_production/current$ rbenv 2.2.2
rbenv: no such command `2.2.2'
deploy@localhost:~/apps/carmel_production/current$ rbenv local 2.2.2
deploy@localhost:~/apps/carmel_production/current$ rbenv versions
* 2.2.2 (set by /home/deploy/apps/carmel_production/current/.ruby-version)
deploy@localhost:~/apps/carmel_production/current$ ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
deploy@localhost:~/apps/carmel_production/current$ bundle exec unicorn -D -c /home/deploy/apps/carmel_production/shared/config/unicorn.rb -E production

Capistrano Deployment fails due to rake db:migrate failure

The cause is that the database does not exist.

Create a Database on the Server Manually

sudo -u postgres createdb --owner=postgres your-database-name

To go to postgres console:

sudo -u postgres psql

FATAL: password authentication failed for user "your-user-idl"

The following steps work for a fresh install of postgres 9.4 on Ubuntu 14.04

By default, postgres creates a user named 'postgres'. We log in as that user, and give that user a password.

$ sudo -u postgres psql
\password
Enter password: topseckret

\q

to exit postgres.

Then we connect as 'postgres'. The -h localhost part is important: it tells the psql client that we wish to connect using a TCP connection (which is configured to use password authentication), and not by a PEER connection (which does not care about the password).

$ psql -U postgres -h localhost

PG::ConnectionBad: FATAL: Peer authentication failed for user

Specify the host in database.yml:

production:
  adapter: postgresql
  encoding: unicode
  database: postgresql
  pool: 5
  host: localhost
  username: postgresql
  password: secret

bitbucket Permission denied (publickey). capistrano

You should already have your ssh keys added to your Bitbucket account. From the root of the rails project run:
1. ssh-add ~/.ssh/id_rsa
2. cap production deploy



sudo stderr: sudo: no tty present and no askpass program specified

1. Login to the server as root
2. Add the following line to the end of sudoers file by doing : visudo
deploy ALL=(ALL) NOPASSWD: ALL

Installing pg gem on Mac OS 10.9.5

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /Users/bparanj/.rvm/rubies/ruby-2.1.5/bin/ruby -r ./siteconf20150623-1849-zuaatt.rb extconf.rb 
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/Users/bparanj/.rvm/rubies/ruby-2.1.5/bin/ruby
--with-pg
--without-pg
--enable-windows-cross
--disable-windows-cross
--with-pg-config
--without-pg-config
--with-pg_config
--without-pg_config
--with-pg-dir
--without-pg-dir
--with-pg-include
--without-pg-include=${pg-dir}/include
--with-pg-lib
--without-pg-lib=${pg-dir}/lib

extconf failed, exit code 1

Gem files will remain installed in /Users/bparanj/.rvm/gems/ruby-2.1.5@carmel/gems/pg-0.18.2 for inspection.
Results logged to /Users/bparanj/.rvm/gems/ruby-2.1.5@carmel/extensions/x86_64-darwin-14/2.1.0-static/pg-0.18.2/gem_make.out
An error occurred while installing pg (0.18.2), and Bundler cannot continue.

Make sure that `gem install pg -v '0.18.2'` succeeds before bundling.

RESOLUTION : 

1. Install http://postgresapp.com/
2. Move postgres from Downloads folder to the Applications folder
3. gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config


Monday, June 22, 2015

Upgrading Ruby using Sunzi

# rbenv
# $1: ruby version

# This condition will not work if we want to upgrade Ruby. Fix is needed.
if [ -d /usr/local/rbenv ]; then
  echo 'rbenv already installed, skipping.'
else
  git clone git://github.com/sstephenson/rbenv.git /usr/local/rbenv
  echo 'export RBENV_ROOT=/usr/local/rbenv' >> /etc/profile.d/rbenv.sh
  echo 'export PATH="$RBENV_ROOT/bin:$PATH"' >> /etc/profile.d/rbenv.sh
  echo 'eval "$(rbenv init -)"' >> /etc/profile.d/rbenv.sh
  chmod +x /etc/profile.d/rbenv.sh
  source /etc/profile.d/rbenv.sh
  pushd /tmp
    git clone git://github.com/sstephenson/ruby-build.git
    cd ruby-build
    ./install.sh
  popd
  echo "Compiling Ruby. Grab some hot chocolate, this will take a while..."
  rbenv install $1
  rbenv global $1
  gem install bundler --no-ri --no-rdoc
  rbenv rehash
fi

I had to blow the entire /usr/local/rbenv to force the upgrade. Just specifying the version in sunzi.yml:

attributes:
  environment: production
  ruby_version: 2.2.2

does not work.

Using Sunzi Gem to Provision Your Server in Minutes

Sunzi is the easiest server provisioning utility designed for mere mortals. If Chef or Puppet is driving you nuts, try Sunzi! Here is step-by-step instructions on  : Provisioning a Server using Sunzi