Sunday, June 18, 2017

Test Behavior vs Implementation

You might have heard that in Rails model:

      validates_presence_of :name
can be tested using helpers like:

should_validates_presence_of :name

The problem with this kind of testing is that it is tied to this specific implementation of validation. If you change the validation to use it's own custom object, this test will break. This is not a good idea.

Wednesday, June 14, 2017

Conversion Points

Conversion Points

Every time your audience is asked to take an action within your sales funnel some users fall off. The key to a highly profitable funnel is to optimize each one of these conversion points.
Let's see which conversion points matter most, how to optimize them, and the 4 main metrics you should track if you want to profit.
  • Lead Magnet
  • Opt-In
  • Email Followups (Open Rates)
  • Order Form Conversion
  • Upsell
Every single step in the sales process is a conversion point. Every kind of sales funnel has it's own conversion points. Take a look at your existing funnel and identify all the conversion points. Conversion rates in sales page is one of the conversion point in the sales process. But the entire sales process must be optimized. 

Key Metrics

  • Cost of Customer Acquisition 
  • Life-Time Customer Value      (Triple the initial sale, in two years or so).
  • Cost Per Lead 
You can buy PDF template at Graphic River  and use it to create PDF documents.

Wednesday, June 07, 2017

Possible Rack Cache Issue

I had to remove rack-cache to figure out why articles index page did not display all articles when a user clicked on a tag to get related articles.

First remove the rack-cache gem, delete rack-cache gem in Gemfile and run bundle. To troubleshoot this problem, in production.rb set:

config.assets.compile = true

In your development machine (not production) run:

bundle exec rake assets:precompile returned 1 instead of one of [0]

This gave a clue that there was a reference to rack-cache in application.rb.

rake assets:precompile --trace RAILS_ENV=production
** Invoke assets:precompile (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
rake aborted!
LoadError: cannot load such file -- rack/cache Be sure to add rack-cache to your Gemfile
/Users/bparanj/.rvm/gems/ruby-2.3.1@lafon/ge


Remove    

config.action_dispatch.rack_cache = true from application.rb

Redeploy the code and from rails console production in the production machine, run:

Rails.cache.clear

to clear the cache. The problem turned out to be not related to rack-cache. At least one of the suspect has been ruled out. I temporarily disabled the find related articles by tag.

Monday, June 05, 2017

Tagging Multiple Models in Rails Notes

```ruby
class TagMultipleModels < ActiveRecord::Migration
  def change
    rename_column :taggings, :episode_id, :taggable_id
    add_column :taggings, :taggable_type, :string, :default => 'Episode'
    remove_foreign_key :taggings, :episodes
  end
end
```

rake db:rollback

StandardError: An error has occurred, all later migrations canceled:

Add a new migration for:     remove_foreign_key :taggings, :episodes

rails g migration remove_foreign_key_for_taggings


ActiveRecord::InvalidForeignKey


Delete teh new migration and create a new article instead of editing an existing record in an invalid state.


SELECT column FROM table WHERE column NOT IN
(SELECT intended_foreign_key FROM another_table)

select taggable_type from taggings where taggable_type NOT IN (select taggable_id from episodes);

Mysql2::Error: Cannot add or update a child row: a foreign key constraint fails


Mysql2::Error: Cannot add or update a child row: a foreign key constraint fails (`chico_development`.`taggings`, CONSTRAINT `fk_rails_18a01188f6` FOREIGN KEY (`taggable_id`) REFERENCES `episodes` (`id`)): INSERT INTO `taggings` (`taggable_type`, `tag_id`, `taggable_id`, `created_at`, `updated_at`) VALUES ('Article', 542, 4752, '2017-06-06 03:14:34', '2017-06-06 03:14:34')


Import data from production. Merge the last two new migrations to one migration:


brew install elasticsearch

==> Using the sandbox
==> Downloading https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.4.1.tar.gz
######################################################################## 100.0%
==> Caveats
Data:    /usr/local/var/elasticsearch/elasticsearch_bparanj/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_bparanj.log
Plugins: /usr/local/opt/elasticsearch/libexec/plugins/
Config:  /usr/local/etc/elasticsearch/
plugin script: /usr/local/opt/elasticsearch/libexec/bin/elasticsearch-plugin

To have launchd start elasticsearch now and restart at login:
  brew services start elasticsearch
Or, if you don't want/need a background service you can just run:
  elasticsearch
==> Summary
  /usr/local/Cellar/elasticsearch/5.4.1: 100 files, 35.4MB, built in 1 minute 7 seconds


elasticsearch

org.elasticsearch.bootstrap.StartupException: java.lang.IllegalStateException: failed to obtain node locks, tried [[/usr/local/var/elasticsearch/elasticsearch_bparanj]] with lock id [0]; maybe these locations are not writable or multiple nodes were started without increasing [node.max_local_storage_nodes] (was [1])?


$ brew remove elasticsearch
$ sudo rm -rf /usr/local/var/elasticsearch
$ sudo rm -rf /usr/local/etc/elasticsearch

$ brew install elasticsearch

brew install elasticsearch
==> Using the sandbox
==> Downloading https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.4.1.tar.gz
Already downloaded: /Users/bparanj/Library/Caches/Homebrew/elasticsearch-5.4.1.tar.gz
==> Caveats
Data:    /usr/local/var/elasticsearch/elasticsearch_bparanj/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_bparanj.log
Plugins: /usr/local/opt/elasticsearch/libexec/plugins/
Config:  /usr/local/etc/elasticsearch/
plugin script: /usr/local/opt/elasticsearch/libexec/bin/elasticsearch-plugin

To have launchd start elasticsearch now and restart at login:
  brew services start elasticsearch
Or, if you don't want/need a background service you can just run:
  elasticsearch
==> Summary
/usr/local/Cellar/elasticsearch/5.4.1: 100 files, 35.4MB, built in 12 seconds
$elasticsearch

  Article Store (14.7ms)  {"id":5091,"exception":["Faraday::ConnectionFailed","Couldn't connect to server"]}
Completed 500 Internal Server Error in 50ms (Searchkick: 14.7ms | ActiveRecord: 9.6ms)


Rails.cache.clear if new production import does not show new episodes.

Sunday, May 28, 2017

Monday, May 22, 2017

Removing Turbolinks from Rails 4

Turbolinks created problem with Stripe payment processing javascript and also with ouibounce javascript. I finally decided to remove it from my Rails 4 project. To remove Turbolinks with your Rails 4 application:
  1. Remove the gem 'turbolinks' line from your Gemfile.
  2. Remove the //= require turbolinks from your app/assets/javascripts/application.js.
  3. Remove the two "data-turbolinks-track" => true hash key/value pairs from your app/views/layouts/application.html.erb

Monday, May 15, 2017

Start with a Platform, and Then Use it for Everything

What Amazon Gets it Right
Six Reasons to Split Front End and Back End code into Two Git Repositories
Let's keep frontend outside of Ruby
The case for separating front and back
Splitting Monolithic Rails Applications

Another good reason to separate the front-end as a separate app from the backend is that front-end developers can evaluate their design by seeing what the pages look like with different datasets. They can use dummy data that conforms to the JSON API. They don't have to wait for the backend developers to complete the development.

Thursday, May 11, 2017

Setting Application Dimensions in Mac for Screencasting

#!/usr/bin/env bash

echo "Setting $1 bounds to 720p"

# 720p is 1280x720. 
# Bounds is startX, startY, endX, endY. Adjust size from starting position to account for this
osascript -e "tell application \"$1\" to set the bounds of the first window to {250, 220, 1530, 940}"

# activate the app, to bring it to the front
osascript -e "tell application \"$1\" to activate" 

Gist 

sudo chmod +x ./dimension.sh

dimension Terminal
dimension Chrome
dimension Safari
dimension Textmate

These commands automatically resizes the application dimensions with very minimal effort for screencasting. This script is stolen  from Screencasting Tip: Resize Your App To 720p (1280×720) In OSX.


Tuesday, May 09, 2017

CORS



Using HTTP/2 to Speed Up Performance of Rails App

If you are using Cloudfront in your Rails app, any new Cloudfront distribution you create after Amazon started to support HTTP/2 will automatically default to supporting HTTP/2 if the browser is capable of taking advantage of it. If you created a Cloudfront distribution before Amazon started to support it, you have to edit the existing configuration and change the selection as shown in the image.

Sunday, May 07, 2017

No site key specified. recaptcha rails

In recaptcha gem version 3.3.0, the credential names was:

RECAPTCHA_PRIVATE_KEY
RECAPTCHA_PUBLIC_KEY

In recaptcha gem version 4.3.1, they are called:

export RECAPTCHA_SITE_KEY= '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
export RECAPTCHA_SECRET_KEY='6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'

So:

RECAPTCHA_PUBLIC_KEY is now called RECAPTCHA_SITE_KEY and RECAPTCHA_PRIVATE_KEY is now called RECAPTCHA_SECRET_KEY.

You can set these environment variables in the .profile file in the home folder of your production server.

Since the recaptcha gem does not have any release notes, you have to compare different releases and look at the diff:

https://github.com/ambethia/recaptcha/compare/v3.4.0...v4.0.0

Comparing different versions I created a release notes on the wiki:

  • 4.0.0 : Name of the credentials environment variable names changed
  • 4.1.0 : Add Invisible reCAPTCHA implementation feature
  • 4.2.0 : Make URLs configurable
  • 4.3.0 : Allow random attributes to be rendered for invisible captcha button
  • 4.3.1 : Add site key back to data attributes

not able to scroll up in terminal mac os

Run:

reset

in the terminal.

Sprockets Deprecation

** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns: DEPRECATION WARNING: You are using the a deprecated processor interface #.
 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns: Please update your processor interface:
 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns: https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors
 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns:  (called from install at /srv/lafon/shared/bundle/ruby/2.3.0/gems/autoprefixer-rails-6.3.7/lib/autoprefixer-rails/sprockets.rb:37)
 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns: DEPRECATION WARNING: Sprockets method `register_engine` is deprecated.
 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns: Please register a mime type using `register_mime_type` then
 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns: use `register_compressor` or `register_transformer`.
 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns: https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors

 ** [out :: rp] Notice: /Exec[bundle exec rake assets:precompile]/returns:  (called from block (2 levels) in at /srv/lafon/shared/bundle/ruby/

https://github.com/rails/sass-rails/issues/381

  1. Add the sass rails gem to the the GemFile
    a) gem 'sass-rails', '~> 5.0', '>= 5.0.6'
  2. Run gem install sass-rails on the terminal
    a) gem install sass-rails
  3. Run bundle install
    a) bundle install --without production && bundle update

Saturday, May 06, 2017

pg_search Rails 5.1 Incompatibility

pg_search (2.0.1) is not compatible with Rails 5.1


rails db:migrate
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:


  class CreatePgSearchDocuments < ActiveRecord::Migration[4.2]

shadow effect in CSS

Define a class :

.paper {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

Use it for the pages.

Thursday, May 04, 2017

Tuesday, May 02, 2017

ExecJS::RuntimeError rails


Resolution: 

Add the gem to Gemfile:

gem 'therubyracer', platforms: :ruby

Run bundle install.

Monday, May 01, 2017

Consuming JSON API using jQuery

Rails 5 jQuery .ajax method data format
How to render JSON from an ajax request in rails?
Rails with jQuery Ajax GET
Ruby on Rails: POST a JSON Array
Saving data with ajax in rails
Get progress of AJAX call to get JSON in Rails
Rails - ajax response handling
Ajax Bad Request 400 Rails


Simple Example to Consume JSON using jQuery
How to Use JSON APIs with jQuery
(JSONP to make calls to external domains)
JSONP Examples
jQuery JSON Docs


Sunday, April 30, 2017

Using whenever gem with Rails

To list what crons are installed:
crontab -e

whenever gem is integrated with Capistrano.

gem 'whenever', require: false

wheneverize .

bundle exec wheneverize .

config/schedule.rb

Add:

every 1.day, at: '4:30 am' do
  rake 'clear_cache'
end

task clear_cache: :environment do
  Rails.cache.clear
end

bundle exec whenever

Backup prod db
Populate download geo co-ordinates once every day

When payment fails, send email using ActionMailer

For Capistrano integration, in config/deploy.rb:
require 'whenever/capistrano'

Monday, April 24, 2017

jQuery Turbolinks Stripe Subscription Problem

https://github.com/kossnocorp/jquery.turbolinks is a possible fix, the problem is that it is not compatible with newer versions of Turbolinks.

The workaround is to either not use different application layout files (one with stripe.js and one without stripe.js), so you have only one layout that has stripe.js or you can have two layouts but still include stripe.js on both. Eventhough only your payment pages need the stripe.js and results in a little duplication and might affect the performance in a very negligible amount, this will prevent the Turbolinks problem.

If you had used Rails cache to cache the pages, you must invalidate the cache by running in production:


 Rails.cache.clear

This will force the page to pickup the changes made to the layout files, otherwise you will see the latest file in the production but the browser will not see the updated file.

Tuesday, April 18, 2017

Bootstrap 4 Material Design Links

1. Bootstrap Material Design Components
2. Demo

Upgrading Passenger from 5.0 to 5.1 using Moonshine

Change passenger version in passenger.rb:

  BLESSED_VERSION = '5.1.2'

Checkin the file and cap deploy. This version of passenger turns on XSS security header:


X-XSS-Protection: 1; mode=block

Thursday, April 13, 2017

Making the Transition from Blogger to an Author

How did I make the transition from writing blog posts to a book author? Initially I was writing only 'How-To' articles that focused on helping the reader get a specific result. Over time, as I wrote more I gained more confidence and I was able to write more articles in less time. However, writing a book is more involved than writing blog posts. I am not a native English speaker. It pushed me beyond my writing abilities. Since I did not have any training in writing, I searched for resources on how to write technical books. I had to learn some techniques that helped me write the book during the time I worked on the TDD in Ruby book. Today, I am going to share with you one of the techniques that I learned during the time I wrote the book. I had the main bullet points and I used Semantic Maps to expand the main points to a paragraph.

Semantic maps are webs of words. The purpose of creating a map is to visually display the meaning-based connections between a word or phrase and a set of related words or concepts.

I would take the main point, research the topic and draw the semantic map that connects all the concepts. I would then eliminate the concepts that are not relevant to the analogy that I need to explain the main idea. I revised the diagram over the course of few days. Then I write a paragraph by referring the semantic map. I revise the paragraph several times. I keep all the paragraphs next to each other so that I can compare and finally pick the one that I am satisfied with.

The following diagram shows the semantic map for the music analogy that I used in the book. The music-semantic-map-1 shows how the music is related to other concepts. The concepts are connected by arrows and the relationship is written next to the arrows. The music-semantic-map-2 is the continuation of the map that connects the Performer to musical instruments.

I also drew semantic maps for programming as shown in program-semantic-map-0 and program-semantic-map. I compare the semantic maps that captures the essence of creating music with creating computer programs, I look for things that are similar to make the analogy clear.


Comparison of semantic maps helps us to find missing concepts in the paragraph that expands the main idea. I found semantic maps very helpful because I don't need to worry about grammar when I am drawing them. The main focus is in finding the essential relationships between the concepts. Once I nailed the relationships between the concepts then I worry about the grammar and the sequence of the sentences to form a paragraph. The TDD in Ruby book is written to be practical introduction TDD for Ruby developers. I hope you enjoy this book as much as I enjoyed writing it.

Friday, April 07, 2017

Ruby on rails Developer - Palo Alto

Rate can be over $100 for the right candidate. If interested, email me at bparanj at gmail dot com.

Job Details:
Position: Sr.
Software Engineer (Ruby on rails Developer)
Location: Palo Alto, CA
Duration: 3+ Months contract with possibility of Extension

Job Description:
Responsibilities:
· Create progressive solutions to solve complex test automation challenges.
· Collaborate with the QA team to architect, develop, and maintain an innovative test automation system for the organization, with respect to functionality, performance, scalability and other quality goals.
· Apply Development and QA Best Practices and actively look for process improvement opportunities.
· Develop and maintain automated test systems.
· Mentor and assist QA Engineers in the use of automation tools.
· Maintain test environments and test automation systems (install/update software on remote and/or virtual systems).
· Provide feedback to internal teams on application flexibility, consistency, and user-friendliness, and provide information to help business stakeholders make the best decisions possible.
· Provide the team with risk assessment and risk mitigation strategies.
· Research, analyse, report, and track defects through completion.
Skills & Requirements

Education:
· Bachelor's degree in Computer Science / Information Systems or an equivalent combination of education and work experience.
Qualifications:

Skills:
· 5+ years of development / test automation experience, preferably with complex web applications using Ruby or other OO languages.
· 3+ years of experience working specifically in or with QA teams.
· 3+ years of experience with SQL (MySQL preferred).
· Knowledge of Windows / Linux / OS X operating systems is a plus.
· Familiarity with Agile development principles is a plus.
· Desire to learn from and mentor other team members, including paired programming practices.
· Demonstrated ability to become a subject matter expert.
· Knowledge and experience with Continuous Integration, Continuous Build and Continuous Deployment practices, tools and trends.
· Experience with virtualization technologies such as VMWare, Hyper-V, OpenStack, etc. preferred.
· Understanding of SaaS infrastructure and components (RDBMS, Web and Application Servers, Queues, Caching, etc.).
· Experience with Ruby is preferred.
· Working knowledge of Ruby on Rails and ability to read and interpret intent in a large application is a huge plus.
· Experience with source code revision control systems such as GIT or SVN.
· Highly detail oriented and well organized.
· Strong analysis and problem-solving skills.
· Ability to identify small inconsistencies throughout a complex system.
· Excellent interpersonal skills, ability to work as part of a team.
· Must be self-motivated and take initiative in performing tasks and growing skills and knowledge.
· Ability to effectively communicate information, both verbally and written, to team members and management.

Sunday, April 02, 2017

How to move contacts from Android

Open Contacts, click on ... and click on Move device contacts to, you can select Google and your contacts will be moved to your Google account.

Saturday, March 25, 2017

Developing a Web Application from Requirements.

 Given you are the owner of a veterinary practice, create a basic Rails application that satisfies the following user stories:

1. As the owner of the veterinary practice, I have two additional veterinary doctors Bob and Susan. I should be able to track the following information about myself and my fellow veterinary doctors.

Name - must be no longer than 35 characters; value is required
Address
City
State
Zip - should be at most 5 digits
School Received Degree From
Years in Practice - must be value between 1-100

2. As the receptionist of the veterinary practice, I should be able to schedule an appointment for a customer's pet with a specific veterinary doctor. The appointment should contain the following information.

Date of Visit - date cannot be in the past; value is required
Pet - required
Customer -required
Requires Reminder of Appointment
Reason for Visit – required

3. As one of the practicing veterinary doctors, I should be able to record the following information about a customer's pet.

Name of Pet - required, no more than 35 characters
Type of Pet - must be a dog, cat, or bird
Breed - required, no more than 35 characters
Age - required
Weight - required
Date of Last Visit – required

4. As a customer, I should be able to see when my pet is scheduled for their next appointment

Pet's Name
Date of Next Appointment
Reason for Visit


Saturday, March 18, 2017

How to split videos in command line

The command:

ffmpeg -i source-file.foo -ss 0 -t 600 first-10-min.m4v

will work but is slow. Solution:

ffmpeg -ss 00 -t 00:01:0.0 -i source.mp4 -vcodec copy -acodec copy result.mp4

Will split the source.mp4 from the beginning to the first 60 seconds and save it in result.mp4.

Friday, March 17, 2017

How to Concatenate Video Files

I needed to stitch intro and outro to my screencast video. I installed ffmpeg on my mac, created a text file, stitch.txt:

file './intro.mp4'
file './semantics3.mp4'

file './outro.mp4'

To stitch videos:

ffmpeg -f concat -safe 0 -i mylist.txt -c copy output.mp4

Install ffmpeg on Mac

To concatenate intro and outro to my screencasts, I use ffmpeg to stitch the videos from the command line. It is faster and easier than using the ScreenFlow.

brew options ffmpeg

brew install ffmpeg --with-fdk-aac --with-ffplay --with-freetype --with-frei0r --with-libass --with-libvo-aacenc --with-libvorbis --with-libvpx --with-opencore-amr --with-openjpeg --with-opus --with-rtmpdump --with-schroedinger --with-speex --with-theora --with-tools


Sunday, March 12, 2017

How to Setup Textmate to use RVM

Go to Textmate preferences, click on Variables and create a TM_RUBY variable the value should be set to the output of the which rvm-auto-ruby command run in the terminal. The changes will take effect without requiring any restart of textmate.

Sunday, March 05, 2017

configure: error: clang version 3.0 or later is required

~ $gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix
~ $clang -v
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0

Thread model: posix

Monday, February 27, 2017

Mac OS 10.10.5

Type gcc in a terminal, install GCC by clicking the popup window.

Install Brew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

brew install gnupg gnupg2

gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3


\curl -sSL https://get.rvm.io | bash

Rails 5.1 and Webpack Tutorial

https://medium.com/@gauravtiwari/hey-bp-strange-is-webpack-dev-server-installed-5c1ec83517e8#.fci5ohl22
 
brew update
brew install yarn 
yarn add webpack-dev-server
 
 

Friday, February 24, 2017

Learning to be awesome at anything you do, including being a leader | Tasha Eurich

Step 1 is to know thyself.
Then on the right hand side for each skill, on a scale of 1 to 10,
I want you to imagine that you only got better at that,
and then rate how much more awesome you would be.
Start with the highest number and work your way down.
So, you know yourself, you've got your one thing.
What makes someone exceptional is that they earn it through daily practice.
Everyday on his way to work he'd think about what he was trying to improve,
and he'd make a plan to practice it.
Then on the way home, he would think about how he did,
and maybe some ideas for what he would the next day.
In sum total, Steve probably spent less than 30 minutes a week doing this,
and he saw massive returns.
So, everyday, I want you to jump out of bed and say,
"Today is the day I'll get better at my one thing!"
But every day you'll learn, and every day you'll get better.
Know thyself. Pick one thing. Practice daily.

Friday, February 17, 2017

Horrible Coding by Amazon Developers

If you do not have Internet connectivity, it will crash with meaningless error:

Users/bparanj/.rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect returned=1 errno=0 state=error: certificate verify failed (Seahorse::Client::NetworkingError)

This can also happen if you do not click on agree button when you are on starbucks coffee shop.

If you provide a invalid file in a s3 bucket, aws-sdk version 2 will crash with meaningless error message:

 # []>>
ArgumentError: expected params[:key] to be a String, got value []> (class: Rake::FileTask) instead.

You must provide a valid file name. The library is not capable of telling you the cause of the problem and how to fix it. It will crash inside aws-sdk-core with an ugly stack trace:

/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/param_validator.rb:28:in `validate!'
/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/param_validator.rb:13:in `validate!'
/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/plugins/param_validator.rb:20:in `call'
/gems/aws-sdk-core-2.7.0/lib/seahorse/client/plugins/raise_response_errors.rb:14:in `call'
/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/plugins/s3_sse_cpk.rb:19:in `call'
/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/plugins/s3_dualstack.rb:24:in `call'
/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/plugins/s3_accelerate.rb:34:in `call'
/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/plugins/idempotency_token.rb:18:in `call'
/gems/aws-sdk-core-2.7.0/lib/aws-sdk-core/plugins/param_converter.rb:20:in `call'
/gems/aws-sdk-core-2.7.0/lib/seahorse/client/plugins/response_target.rb:21:in `call'
/gems/aws-sdk-core-2.7.0/lib/seahorse/client/request.rb:70:in `send_request'
/gems/aws-sdk-core-2.7.0/lib/seahorse/client/base.rb:207:in `block (2 levels) in define_operation_methods'
/gems/aws-sdk-resources-2.7.0/lib/aws-sdk-resources/request.rb:24:in `call'
/gems/aws-sdk-resources-2.7.0/lib/aws-sdk-resources/operations.rb:41:in `call'
/gems/aws-sdk-resources-2.7.0/lib/aws-sdk-resources/operations.rb:61:in `call'
/gems/aws-sdk-resources-2.7.0/lib/aws-sdk-resources/resource.rb:147:in `load'
/gems/aws-sdk-resources-2.7.0/lib/aws-sdk-resources/resource.rb:120:in `data'
/gems/aws-sdk-resources-2.7.0/lib/aws-sdk-resources/resource.rb:223:in `block in add_data_attribute'

/gems/railties-4.2.7/lib/rails/commands/console.rb:110:in `start'
/gems/railties-4.2.7/lib/rails/commands/console.rb:9:in `start'
/gems/railties-4.2.7/lib/rails/commands/commands_tasks.rb:68:in `console'
/gems/railties-4.2.7/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
/gems/railties-4.2.7/lib/rails/commands.rb:17:in `'





AWS SDK Ruby


Aws::Errors::MissingRegionError
Aws::Errors::MissingCredentialsError (unable to sign request without credentials set). In aws sdk version 2:

    Aws.config = {
      region: 'us-east-1',
      credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
    }

Tuesday, February 14, 2017

Ruby Gems Naming Convention

How does the gem name and the require relate to each other? Should I use underscore of the gem name? Should I use / ?

The screenshot shows the rubygems recommendation for naming conventions and how developers can require a ruby gem. This also makes it clear how the directory structure is related to the require of the gem. You can see whether it is a class or module and how the namespace relates to requiring a gem.

Sunday, February 12, 2017

Readline was unable to be required, if you need completion or history install readline then reinstall the ruby.

1. brew install openssl --force


2. rvm requirements
Checking requirements for osx.
Updating Homebrew...
Installing requirements for osx.
Updating system.....
Installing required custom packages: homebrew/versions.
Installing required packages: zlib, zlib, gcc46, openssl.............
Somehow it happened there is no executable 'openssl',
run 'brew doctor' and make sure latest '' is installed properly.
RVM autolibs is now configured with mode '4' =>
  'Allow RVM to use package manager if found, install missing dependencies, install package manager (only OS X).',
please run `rvm autolibs enable` to let RVM do its job or run and read `rvm autolibs [help]`
or visit https://rvm.io/rvm/autolibs for more information.

Requirements installation failed with status: 12.

3. rvm pkg install readline
Beware, 'rvm pkg ...' is deprecated, read about the new autolibs feature: 'rvm help autolibs'.

rvm reinstall all --force


Twitter Bootstrap 4 Testimonials


Friday, February 10, 2017

How to migrate your RSS feed in Rails

I am migrating from libsyn to save $40 / month. I host all the videos on S3 saving lot of money. If you go live with your RSS feed pointing to libysyn when you switch over to your Rails rss feed, you must add:

xml.itunes :"new-feed-url", 'https://www.rubyplus.com/episodes.rss'

in index.rss.builder inside the channel tag to migrate successfully. This is in addition to logging in to your libshit account and changing the RSS feed to point to your new feed generated by your Rails app.

Thursday, February 09, 2017

How to set default date in date_select of Rails 5

You can use the selected option to specify the default date.

    <%= f.date_select :published_at, order: [:month, :day, :year], start_year: Date.current.year - 5, end_year: Date.current.year + 1, selected: @date %>

In my case, I set it in the controller to today's date:

@date = Date.today


Tuesday, February 07, 2017

Rails Assets


$ is not defined error in Rails

I followed the Google Page Speed Guidelines and made the javascript load asynchronously to speed up rubyplus.com. The problem was that I was getting the $ is not defined error. I had included the javascript tag before the jQuery script that hides the notice. Eventually, I came across this post:
Rails 4 Gotcha Asynchronous Loading of Javascript that finally fixed the problem. The fix is:

Change:

  <%= javascript_include_tag "application", "data-turbolinks-track" => true, async: true %>

to

  <%= javascript_include_tag "application", "data-turbolinks-track" => true, async: Rails.env.production? %>

I know this is a quick hack. Ideally, we should define a configuration variable to read and set the flag value in development.rb and production.rb. That's for another iteration and deploy. It works in development, now, I will see how it works in production for some time.

RubyPlus Download Stats


Sunday, February 05, 2017

DataTables using Twitter Bootstrap 4


No database selected

Provide the database name using --database switch when you want to import data into your database in MysSQL.

mysql -u root --database=your-db < data.dump.sql

Saturday, February 04, 2017

Friday, February 03, 2017

brew update fails

$ brew update

error: Your local changes to the following files would be overwritten by merge:
README.md
Please, commit your changes or stash them before you can merge.
Aborting
Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master

Fix:

cd `brew --prefix`
git remote add origin https://github.com/mxcl/homebrew.git
git fetch origin
git reset --hard origin/master

How to Install Clang on Mac Without XCode

I was getting:

configure: error: clang version 3.0 or later is required

when installing ruby 2.3.3 using rvm. Download the Command Line Tools from here:
http://devimages.apple.com/downloads/xcode/command_line_tools_for_xcode_os_x_lion_april_2013.dmg

and install the clang 4.2. I had old 2.1version of clang on my Mac 10.7.5

$ which clang
/usr/bin/clang

clang -v
Apple clang version 2.1 (tags/Apple/clang-163.7.1) (based on LLVM 3.0svn)
Target: x86_64-apple-darwin11.4.2
Thread model: posix