Friday, May 4, 2018

Add syntax Highlighing extension to Sublime for Vue

If like me, you have never added an package to Sublime previously then first you have to add a package manager to your Sublime.

1, Go to the toolbar of you Sublime
Click on: View/Show Console
Go to:
https://packagecontrol.io/installation
I have Sublime Text 3 so I added this code to the console and pressed enter.
import urllib.request,os,hashlib; h = '6f4c264a24d933ce70df5dedcf1dcaee' + 'ebe013ee18cced0ef93d5f746d80ef60'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)
2, Once you do that for your version of Sublime go to
Preferences in your Sublime Toolbar and you'll see a new option:
Preferences/Package Control
Click on that and you will get a pop-up menu.
3. Just type in the thing you are looking for and click on it.

I used Vue Syntax Highlight (I picked it randomly)

This is what my Preferences/Package Settings/Package Control/Settings-Default looks like after I added it.
{
"bootstrapped": true,
"in_process_packages":
[
],
"installed_packages":
[
"Package Control",
"Vue Syntax Highlight"

}
Voila! Now my Vue files are beautiful and have useful highlighting.

Wednesday, February 8, 2017

Naming conventions are important even in Fizz Buzz

I was playing around with Fizz Buzz today.

I started thinking about the dividing part of Fizz Buzz.

I originally was creating 3 methods which I then called in the print_fizzbuzz method.

def divide_by_fifteen(num)
  num % 15
end

def divide_by_three(num)
  num % 3
end

def divide_by_five(num)
  num % 5
end

I realized that I could condense these into one method.

So I went back to math to figure out the best wording for the arguments.

dividend  / divisor == quotient

And thus the final method that is very clear as long as you remember your math.
I added this: ( dividend  / divisor == quotient ) as a comment to be crystal clear.

def divide_by(dividend, divisor)
  dividend % divisor == 0
end

----------------------------------

Then to print the fizz buzz I was looping through a range, for the argument I was using the placeholder num.

I started to think about what I was actually trying to say there.
Instead of just saying num what was it that I really meant?

It took me a while to distill down the words in my head.

First I thought about the problem.
What is "num"? It is the number that I want the Fizz Buzz to stop at.
So I thought end_num, end_number, limit.

When trying to narrow down a word I find it useful to use a Thesaurus
Here are the synonyms for the word limit: http://www.thesaurus.com/browse/limit

These are the words that I thought might be good for my argument after viewing that list:
cap
restraint
bound
conclusion
concludes_at
terminates at
end of range

Then I noticed that I was calling a range.
What could the beginning and the end of a rangebe called?
Answer: lower bound and upper bound


  def print_fizz_buzz(upper_bound)
    fizzbuzz = []
    (1..upper_bound).each do | dividend |
      if divide_by(dividend, 15)
        fizzbuzz << "fizz buzz"
      elsif divide_by(dividend,3)
        fizzbuzz << "fizz"
      elsif divide_by(dividend,5)
        fizzbuzz << "buzz"
      else
        fizzbuzz << dividend
      end
    end
    fizzbuzz
  end



Friday, January 20, 2017

Fun with Ruby and CSV

https://ruby-doc.org/stdlib-2.4.0/libdoc/csv/rdoc/CSV.html

https://www.sitepoint.com/guide-ruby-csv-library-part/

http://technicalpickles.com/posts/parsing-csv-with-ruby/

In Ruby, you can import your CSV file either at once (storing all of the file content in memory) or read from it row-by-row. 

Either way you do it, Ruby will store each table row as an array, with each cell being a string element of the array.

Tuesday, November 29, 2016

Thursday, September 1, 2016

View your Gems and its methods locally with no internet

In this example I am viewing my Devise Gem.
(Your paths will be different than mine.)

$ gem which devise
==> /home/vagrant/.rvm/gems/ruby-2.3.0/gems/devise-4.2.0/lib/devise.rb

$ gem open devise

$ cd /home/vagrant/.rvm/gems/ruby-2.3.0/gems/devise-4.2.0/lib

$  ls
==> devise  devise.rb  generators

$ cd devise/

$ ls
==> controllers     hooks       models.rb    orm                     rails.rb         time_inflector.rb
delegator.rb    mailers     modules.rb   parameter_filter.rb     strategies       token_generator.rb
encryptor.rb    mapping.rb  omniauth     parameter_sanitizer.rb  test             version.rb
failure_app.rb  models      omniauth.rb  rails                   test_helpers.rb

$ cd controllers/

$ ls
==> helpers.rb  rememberable.rb  scoped_views.rb  sign_in_out.rb  store_location.rb  url_helpers.rb

$ cd ..

Here I am looking for the RegistrationsController in all the files with Grep. This is like when you are in Sublime and search all the files.

$ grep -r RegistrationsC .
==> ./rails/routes.rb:    #    class RegistrationsController < Devise::RegistrationsController
./parameter_sanitizer.rb:  # +password_confirmation+ for the `RegistrationsController`), and you can
./parameter_sanitizer.rb:    #    # Inside the `RegistrationsController#create` action.

$ cd rails/

$ ls
==> routes.rb  warden_compat.rb

This is where it is. I open it in vim and look around.
$ vim routes.rb 

Thursday, August 25, 2016

git add with sophictication

I found this git command that I have been looking for forever.
I used to use it then I forgot it and have been googling for it ever since/.

The perfect pairing to git add -p, drum roll please...

git add . -N && git add -p
  • The -N flag means is short for --intent-to-add 
  • git add . -N will stage an empty file representing your newly added file.
    When git add --patch is called 
  • Git will do the normal patch procedure over your newly created file's changes.
  • If no changes are patched in,
    the empty file will not be included in your commit.

Always be sure to check your status!

Sunday, August 14, 2016

Rails Cheat Sheet: Create Models, Tables and Migrations

Create a new table in Rails

rails g model Supplier name:string
rails g model Product name:string:index sku:string{10}:uniq count:integer description:text supplier:references popularity:float 'price:decimal{10,2}' available:boolean availableSince:datetime image:binary
Resulting migrations:
class CreateSuppliers < ActiveRecord::Migration
  def change
    create_table :suppliers do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.string :sku, limit: 10
      t.integer :count
      t.text :description
      t.references :supplier, index: true, foreign_key: true
      t.float :popularity
      t.decimal :price, precision: 10, scale: 2
      t.boolean :available
      t.datetime :availableSince
      t.binary :image

      t.timestamps null: false
    end
    add_index :products, :name
    add_index :products, :sku, unique: true
  end
end

Rails migration to add a column

rails g migration AddKeywordsSizeToProduct keywords:string size:string
Resulting migration:
class AddKeywordsSizeToProduct < ActiveRecord::Migration
  def change
    add_column :products, :keywords, :string
    add_column :products, :size, :string
  end
end

Rails migration to remove a column

rails g migration RemoveKeywordsFromProduct keywords
Resulting migration:
class RemoveKeywordsFromProduct < ActiveRecord::Migration
  def change
    remove_column :products, :keywords, :string
  end
end

Rails migration to rename a column

rails g migration RenameProductPopularityToRanking
You need to add the rename_column command manually to the resulting migration:
class RenameProductPopularityToRanking < ActiveRecord::Migration
  def change
    rename_column :products, :popularity, :ranking
  end
end

Rails migration to change a column type

rails g migration ChangeProductPopularity
You need to add the change_column command manually to the resulting migration:
class ChangeProductPopularity < ActiveRecord::Migration
  def change
      change_column :products, :ranking, :decimal, precision: 10, scale: 2
  end
end

Running migrations

rake db:migrate
In production:
rake db:migrate RAILS_ENV="production" 

Wednesday, April 13, 2016

Notes on Redis

https://github.com/LARailsLearners/sarcastic_messages_tutorial/blob/master/redis_notes.md#cache-vs-data

Thursday, April 7, 2016

Squashing a commit


  • You just sent a pull request to GitHub.
  • Someone commented on it.
  • You fixed the errors. You added them, commited them and pushed them again. 

This actually adds another commit to that pull request and makes it really hard to read for the person who is trying to accept that commit.

What you can do to combine these commits into one, easy to read commit is to squash them together.

This is officially called squashing a commit.

https://github.com/ginatrapani/todo.txt-android/wiki/Squash-All-Commits-Related-to-a-Single-Issue-into-a-Single-Commit

Squash a commit:
$ git rebase -i HEAD~3

You'll see your commits all mashed together

pick Add to README
pick Add .gitignore
pick Edit README

and a list of options

what you want to do is Put the commit you want at the top and squash the other ones into it by removing the work pick in front of it and replacing that with the letter 's' for squash.

So it looks like this

pick Add to README
s Add .gitignore
s Edit README

save it and force push it to GitHub like this:

$ git push origin branch-name --force


Then instead of doing the whole thing again if you make another change just
git add  
git commit --amend
git push origin branch-name --force

and you can add to you former commit

Monday, March 28, 2016

Group Asset deprecated in Rails 4

There is no longer any reason to declare group :asset endin your Gemfile because it was deprecated in Rails 4.

Do not use this:

group :asset do
  gem 'whatever'
end

http://stackoverflow.com/questions/16406204/why-did-rails4-drop-support-for-assets-group-in-the-gemfile
Previously the assets group existed to avoid unintended compilation-on-demand in production. As Rails 4 doesn't behave like that anymore, it made sense to remove the asset group.
This is explained in more detail in the commit that changed that. I extracted some quotes with the actual answer.
Some gems can be needed (in production) like coffee-rails if you are using coffee templates and the fact that now assets are not precompiled on demand in production anymore.
(not precompiled on demand in production) Means that if you have that gems in production environment in 3.2.x and forget to precompile, Rails will do exactly what it does in development, precompile the assets that was requested. This is not true anymore in Rails 4, so if you don't precompile the assets using the tasks you will get a 404 when the assets are requests.

Rails 4 - Disable Turbo Links

Turbolinks is included in Rails 4. It is meant to implement fast reloading by only reloading changed to your app but I am okay with disabling Turbo links. It messes up a lot of the functionality with gems. (https://plus.google.com/+YehudaKatz/posts/A65agXRynUn)

If you need to refresh your page to see your gem them try disabling turbo links and it probably will be better.

I am trying to use the jQuery date picker. What a pain. There are some really lame, inline work arounds to disable turbo links on a per-line basis but I am just going to see what happens if I disable the entire gem.

So I decided to try the Bootstrap datepicker but then I realized that I am using Skeleton so why would I include all of Bootstrap for that one function. Plus it is no easier.

Back to jQuery UI's date picker

http://guides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks

How Turbolinks Works 

Turbolinks attaches a click handler to all <a> on the page. If your browser supports PushState, Turbolinks will make an Ajax request for the page, parse the response, and replace the entire <body> of the page with the <body> of the response. It will then use PushState to change the URL to the correct one, preserving refresh semantics and giving you pretty URLs.
The only thing you have to do to enable Turbolinks is have it in your Gemfile, and put //= require turbolinks in your CoffeeScript manifest, which is usually app/assets/javascripts/application.js.

If you want to disable Turbolinks for certain links, add a data-no-turbolink attribute to the tag:
<a href="..." data-no-turbolink>No turbolinks here</a>.
Disable Turbolinks
Turbolinks takes over any local link, sends an AJAX request for the content, and replaces the body on your current page with that content.
In your Gemfile remove: 
gem 'turbolinks' 

Run bundle

In your application.js remove:
//= require turbolinks

In your application.html.erb remove:
  <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

Delete any “data-turbolinks-track” attributes in your your other layouts.





Saturday, March 26, 2016

Heroku Reset Database


WARNING: This action will delete your database and it's contents but if that is what you want to do proceed with caution and fully warned.

To reset your database:

(The name of my database is jobby-job - change that to the name of yours.)
heroku pg:reset DATABASE_URL

Then it will ask you:

 !    WARNING: Destructive Action
 !    This command will affect the app: jobby-job
 !    To proceed, type "jobby-job" or re-run this command with --confirm jobby-job

> jobby-job

Resetting DATABASE_URL... done

Then run  $ heroku pg:reset DATABASE_URL --confirm jobby-job

Thursday, February 18, 2016

Fixtures - Mintest

ActiveRecord FixtureSet

rubyonrails.org/testing


funclub/test/fixtures/exercises.yml
arms:
  name: windmills
  sets: 3
  reps: 10
  notes: They are fun but be careful not to go too fast and hurt your shoulders.
  bodypart: arms
  workout_id: 1

core:
  name: situps
  sets: 4
  reps: 25
  notes: A classic stength builder for a beach body.
  bodypart: Abs
  workout_id: 2

To run the tests:
$ bin/rake test test/models/article_test.rb

Tuesday, January 19, 2016

Rails 4 Migrations


http://stackoverflow.com/questions/22815009/add-a-reference-column-migration-in-rails-4

When you already have a users and uploads table and wish to add new relationship between them.

All you need to do is, just generate a migration using following command:rails g migration AddUserToUploads user:references

which will create a migration file as:

class AddUserToUploads < ActiveRecord::Migration
  def change 
    add_reference :uploads, :user, index: true 
  end 
end

Then run the migration using rake db:migrate. This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table) PLUS it will also add an index on the new column.

Sunday, January 17, 2016

CSS was not working on Heroku


Add CSS to Heroku
To load the css and assets I ran:

$ bundle exec rake assets:precompile

That still didn't work so I ran:

$ RAILS_ENV=production bundle exec rake assets:precompile

The response:
rake aborted!  
Devise.secret_key was not set. Please add the following to your Devise initializer:
config.secret_key = (gave me a long number)


It is still not working 12-19-2015 on Linux but it works on Mac

(skeleton works on both)

Tuesday, January 5, 2016

Installing Postgres on Ubuntu

Heroku uses Postgres for their database so it is quite nice to use it as the database for your Rails app. That way there is a seamless transition.

Postgres Command Cheat sheet

This site is helpful if you are a Mac user and can $ `brew install`:
http://www.jackiejohnston.us/blog/setting-up-user-authentication-with-devise/

https://www.codefellows.org/blog/three-battle-tested-ways-to-install-postgresql

http://postgresapp.com/documentation/configuration-ruby.html


I decided to install Postgres it my Ubuntu ThinkPad.


How To Install and Use PostgreSQL on Ubuntu 14.04  https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-14-04

Digital Ocean has great documentation.

sudo apt-get update
sudo apt-get install postgresql postgresql-contrib


How To Setup Ruby on Rails with Postgres  https://www.digitalocean.com/community/tutorials/how-to-setup-ruby-on-rails-with-postgres

Wednesday, September 23, 2015

haiku - add users endpoints

create, index, show, update, using json_api_org serializers, with request specs

An endpoint is simply a route defined by your rails application. In terms of an API hitting that endpoint will serve up a resource from your application, or perform some form of action. An example may explain this better.

Say we have an application that handles users and we want our API to expose the users resource. If we follow RESTful convention for our API we will expose seven distinct 'endpoints' linked to seven distinct 'actions' (index, show, create, update, destroy, new, edit) surrounding users.

When building our API, we would make is so anyone who visits "www.myapp.com/users" via a get request is returned some data representation of all users in our application. "/users" is the endpoint. Likewise performing a post action to "/users" with valid data is how we create new users. "/users" is still the endpoint but under different context. If you wanted data for just a single user, it may look something like "www.myapp.com/users/1" in which case "/users/1" is the endpoint.

Request specs provide a thin wrapper around Rails' integration tests, and are designed to drive behavior through the full stack, including routing (provided by Rails) and without stubbing (that's up to you).

Request specs are marked by :type => :request or if you have set
config.infer_spec_type_from_file_location! by placing them in spec/requests.

With request specs, you can:

  • specify a single request
  • specify multiple requests across multiple controllers
  • specify multiple requests across multiple sessions
Check the rails documentation on integration tests for more information.

RSpec provides two matchers that delegate to Rails assertions:

ruby render_template # delegates to assert_template
redirect_to # delegates to assert_redirected_to

JSONAPI::Serializers is a simple library for serializing Ruby objects and their relationships into the JSON:API format.

Wednesday, January 14, 2015

git

$ git commit -m "commit_message"

Yes I know you can do commit messages right in the command line but I like to be more specific about them. 

So I just type in:
$ git commit

and a text editor pops up for the commit.
I like to un-comment the files being added, changed and deleted. I also like to write a good description. Unless I am in a hurry or feeling particularly lazy this is how I do it.

I think it is the version of Ubuntu I am using or some other reason I am unsure of but when I go to commit my projects to git and pop open the window it opens in the nano editor as default.
I don't like it. I prefer vim. 

So instead of declaring the change in the terminal every time I go to commit I changed the .git/config file.

I did this through the terminal using the ultimate git guide. 

$ git config --global core.editor vim


Tuesday, December 9, 2014