Hack hack hack...

An open journal-- some of it written for you, but most of it is for me.

Pergola

Names

  • Taken
    • ivy
    • trellis
    • grapevine
    • chlorophyll
    • vinify

Building the gem

  • Ryan Bates you stud
  • create the gem with builder before you create files within it.

Removing a file from Github

  • git rm examples/all.rb
  • git rm examples/all.rb --cached leaves a local version

class << self

Reading

  • http://www.gironda.org/2013/02/25/digging-in-the-vineyard-part-1.html

.powconfig

.powconfig
1
2
3
4
5
6
7
8
9
eval $(rbenv init -)

export POW_DOMAINS=dev,test

#because I loaded pow with brew and not manually it was a different path...
export PATH="/usr/local/opt/rbenv/shims:$PATH"

export POW_TIMEOUT=900
export POW_WORKERS=1

Calendar App 1

Setup

  • added a EventTimeValidator to lib. this needed to be updated in the app config file as well so that the autoload path would pick up the changes in the lib dir.
rspec tests on valdidations
1
2
expect(event).to_not be_valid
expect(event.errors[:end_date]).to eq ["must be after start date"]

Git global config github

Uploads

  • we used carrierwave
    • remember to set multipart to true

Extend self

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module A
  class << self
    include A

    def x
      puts 'x'
    end
  end

  def y
    puts 'y'
  end
end

A.x #=> 'x'
A.y #=> 'y'

Method Stubs

  • A method stub is an implementation that returns a pre-determined value. Method stubs can be declared on test doubles or real objects using the same syntax.
E.G.
1
2
3
book.stub(:title) { "The RSpec Book" }
book.stub(:title => "The RSpec Book")
book.stub(:title).and_return("The RSpec Book")

any_instance

  • stub on any instance of a class
    • Use any_instance.stub on a class to tell any instance of that class to return a value (or values) in response to a given message. If no instance receives the message, nothing happens.
1
2
3
4
5
6
7
8
describe "any_instance.stub" do
  it "returns the specified value on any instance of the class" do
    Object.any_instance.stub(:foo).and_return(:return_value)

    o = Object.new
    o.foo.should eq(:return_value)
  end
end

Alias Attribute

  • alias_attribute :value, :url

Chop v. Chomp

  • subtle difference between chop and chomp
1
2
3
4
5
6
7
8
9
10
11
12
13
#chop
"string\r\n".chop   #=> "string"
"string\n\r".chop   #=> "string\n"
"string\n".chop     #=> "string"
"string".chop       #=> "strin"
"x".chop.chop       #=> ""

#chomp
"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"

Setting develop as the default

  • git branch --track develop origin/develop

Formtastic

  • collection groups together elements for a select box
    • include blank false

Deploying

  • need to add new deploy instructions to .git/config file

Nano

  • basic text editor that appears to be pre-loaded…

Offsetting an image and a link

  • use padding to offset an image from its link
    • I use this a lot when putting an icon in front of a link
    • see here for more

Deploying to heroku

  • git push staging develop:master

Each with index

E.G.
1
2
3
@something.each_with_index do |thing,index|
  puts index
end

S3

  • used fog to store the carrierwave uploaded images on AWS
  • needed to config heroku with the heroku config:add ENV_VARIABLE=bucket-name -r staging to make it work
  • in carrierwave.rb need to specify the config.fog_host, but this is NOT the right method. It is supposed to be config.asset_host

xip.io

  • Construct your xip.io domain by appending your application’s name to your LAN IP address followed by .xip.io. For example, if your development computer’s LAN IP address is 10.0.1.43, you can visit myapp.dev from another computer on your local network using the URL http://myapp.10.0.1.43.xip.io/. via

Sweepers and caching actions

  • caches_action :index is all that is needed to cache an action via
  • cache_sweeper :event_sweeper is added to the Events controller to trigger the sweeper…
  • Cache sweeping is a mechanism which allows you to get around having a ton of expire_{page,action,fragment} calls in your code. It does this by moving all the work required to expire cached content into an ActionController::Caching::Sweeper subclass. This class is an observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object in an around or after filter.
  • Rails Guide
  • also need to turn on config.cache_store = :dalli_store, ENV['MEMCACHE_SERVERS']

  • In the context of ActiveAdmin

    • We weren’t expiring the events index page, but were rather expiring the ActiveAdmin page instead. This solved the problem, but more specifically specifying the controller.

Another New MacBook Air Load

RBENV

  • ran into a pow issue not recognizing my gemset -> similar issue to the one here and here.
    • it ended up because I had installed rbenv with homebrew which meant it was in the opts directory. What a pain.
  • the rbenv install went pretty smoothly save for that. Used [this as a guide](http://www.bounga.org/ruby/2012/02/06/pow-using-rbenv/.

PSQL

  • the install went much smoother this time. I used this ref when I ran into problems.

  • this helped on my old air… the app installed without a hitch, but I was missing the creating of the databases.

  • when the psql app wasn’t active

    ♕ psql psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket “/var/pgsql_socket/.s.PGSQL.5432”?

  • after turning it on, I got this

    ♕ psql psql: FATAL: database “Ajonas” does not exist

  • the PATH clearly isn’t right, but by adding rake db:create:all I got the app to bootup.

Bundler and Octopress reinstall

  • bundler wasn’t recognized because of the different ruby version. Installed the new version and gem install bundler as [advised](http://stackoverflow.com/questions/7483515/rake-aborted-no-such-file-to-load-bundler-setup-rails-3-1.

KCA 4

Google Analytics

Arel

  • [Some cool arel queries](http://stackoverflow.com/questions/4402815/is-there-a-particularly-elegant-way-to-do-a-count-query-with-rails-3-arel.
  • used a lamba as shown here, because otherwise the queries will be cached and we were running queries for a day to day basis.
  • ARel has some good documentation.

Local Storage

  • used store.js
  • nice little screencast
  • here is an older article from 2010
  • NOTE: We ended up using store.js with json because ie7 apparently doesn’t come equiped with JSON. Tom and I broke our heads trying to figure out why store.enabled wasn’t true for ie7. It came down to the fact that ie7 didn’t have JSON.

Thought this was a cool little way to store whether a td square had been clicked on…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
addRedTiles: ->
  selected = store.get("board_#{@board_id}")

  for tile_number in selected
    $("[data-title-num=#{tile_number}]").addClass('clicked_space')


duringBoardClick: ->
  if store.enabled
    $('td').click =>
      $(event.target).toggleClass('clicked_space')
      clicked_tiles = []
      all_clicked = $('td.clicked_space')

      for tile in all_clicked
        clicked_tiles.push $(tile).attr('data-title-num')

      store.set("board_#{@board_id}", clicked_tiles)
  else
    console?.log? 'store is not enabled'
This needed to be updated b/c of event.targer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
duringBoardClick: ->
  if store.enabled

    board_id = @board_id
    \\notice that I declared the above variable
    $('td').click -> \\and changed this to a single ->
      $(@).toggleClass('clicked_space')
      clicked_tiles = []
      all_clicked = $('td.clicked_space')

      for tile in all_clicked
        clicked_tiles.push $(tile).attr('data-title-num')

      store.set("board_#{board_id}", clicked_tiles)
      \\board then becomes a local
  else
    console?.log? 'store is not enabled'

I think this was the first time I used the push method in coffeescript.

Z-index

  • in order to use z-index you need to use the position absolute, relative, or fixed as mentioned here

SASS

  • >* selects all the elements in the selector

PG backups

  • Backing up a larger DB on heroku -> docs

Anchor in a path helper

  • pass it in as an option redirect_to post_path(comment.post, :anchor => "comment-#{comment.id}") -> from

Regex

  • remember there is no whitespacing in regex
    • background_\w|clicked_space not background_\w | clicked_space

Background images in mobile

  • need to make sure to explicity define the background image and background size for mobile

KCA 3

  • Everytime you clone a project you get its full history…

    • to get a specific commit
      • $ git checkout -b aNewBranch SHA1 with SHA1 representing the commit id from which you want to proceed.
  • config env variables on heroku

    • heroku config:add FACEBOOK_APP_TOKEN='<tokenhere>' --remote staging
  • rake deploy:staging but need to make sure staging db is up to date rake db:migrate RAILS_ENV=staging

  • custom actions are for dream big are here

  • git bisect -> docs

Expect syntax

  • remember to not including whitespaces between expect and the parentheses
    • correct -> expect(sm.current_number_of_boards).to eq 24
    • incorrect -> expect (sm.current_number_of_boards).to eq 24

Testing the cache

  • it’s not easy to test the cache.

    • one problem is that when you write to the cache you are affecing the dev cache
  • can clear the cache with Rails.cache.clear found here

  • complicated caching

Progress bar

HAML

  • partial -> = render :partial => "partial_name"
  • yield -> #masthead= yield :masthead
  • setting a variable in HAML -> - check_mark = image_tag("http://placehold.it/21x21", class: 'check') need the -
  • submit button -> %input{:type => "submit", :value => "Send", :class => "button"}
sweet helper allows you to reduce whitespace
1
2
= surround 'GiftCard', '.' do
   %sup &reg;

There are a bunch in the docs.

Content_for

Using content_for
1
2
3
4
5
6
7
8
9
<% content_for :not_authorized do %>
  alert('You are not authorized to do that!')
<% end %>

#You can then use content_for :not_authorized anywhere in your templates.
<%= content_for :not_authorized if current_user.nil? %>

#This is equivalent to:
<%= yield :not_authorized if current_user.nil? %>

Escaping a space

Creating or updating many records at a time in rails

1
2
3
4
5
6
7
8
9
#creating new records
["array" "of" "strings"].each_with_index do |t,i|
  Tile.create(:title, t)
end

#updating existing records
["array" "of" "strings"].each_with_index do |t,i|
  Tile.find(i+1).update_attribute(:title, t)
end

Collection in routes

Need collection to lose the id requirement
1
2
3
4
5
resources :superlatives, :only => [:create] do
  collection do
    post :skip
  end
end

.length

You can look for the number of instances in the DOM and update it accordingly if there are the right number. I used this when I was updating the DOM and to see if the page had 3 classes indicating that three friends had been nominated.

Need collection to lose the id requirement
1
2
if $('div.friend-nomination').length == 3
  console?.log? 'this has three'

Heroku console

  • heroku run rails console --remote <name of branch> or heroku run console -r <name of branch> for short

CSS Positioning

Print Stylesheets

  • had a problem with getting the @media print file to recognize the sass styling that I was writing. Discovered that every single element needed to be to explicitly defined for it to work…. what a pain in the ass.

JQuery Migrate

Paypal Integration

IPN

instant payment notification

  • Paypal will provide an asynch call made to our server from paypal to update us of the status.
    • this is asynch so it could take a few seconds or it could take more.

KCA 2

Heroku

  • git push staging develop:master

FB

  • target ‘_top’ will put the new window on top
  • http://app.facebook.com/name-space
  • make sure to disable secure browsing in FB
  • change fields from address state to state_loc to avoid collisions with state machine gems like transitions

  • can simulate mobile with overrides in the inspector

  • heroku run rake db:migrate --remote staging

  • heroku config:add <env variable> <env variable>
  • heroku log --remote staging

  • .shuffle method

  • .floor returns an integer
  • if diving two integers you need to th make sure one of them is a float

  • In routes, member do block adds a resource on a specific record, while collect do

  • in config/application.rb in order to load libs automatically need to change config to config.autoload_paths += %W(#{config.root}/lib)

  • has_mobile_fu false in appcontroller, need false

  • decent exposure

      • expose(:articles) { current_user.articles } scopes articles belonging to that user
  • output the boards on board show page, new board page, and how to play

  • content tag

    • need to use .html_safe
  • to start memcache /usr/local/opt/memcached/bin/memcached

  • deploy to heroku staging with git push staging develop:master

  • creating a table with content tags in a helper

  • .update_attribute! versus .update_attribute -> raise an exception rahter than false.

Tests

HAML

1
2
.shuffle.hidden
.delete.hidden

Makes divs with classes above

Ajax with coffeescript

Used the call below to make a friend request.

1
2
3
4
5
getFriends: (callback) ->
    FB.api '/me/friends', (response) => 
      $.each response.data, (k, v) =>
        @friends.push({ label: v.name, value: v.id })
      callback()

The callback is to ensure that other function do not proceed before the friends are loaded asynchronously.

Auto-complete with JQuery UI

  • Got it from here
  • also loaded the js and css minified versions in the lib directory.
  • there was a small change to be made, documented here

Javascript to coffee

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  sendMessage: (fb_uid, details = {}) ->
    obj =
      to: fb_uid
      method: "feed"
      redirect_uri: "http://kca.dev"
      link: "http://google.com"
      picture: "http://fbrell.com/f8.jpg"
      name: "Facebook Dialogs"
      caption: "Reference Documentation"
      description: "Using Dialogs to interact with users."

    obj = $.extend obj, details

    FB.ui obj, ->
      alert 'posted'
  • = link_to "Something", some_path, :method => :post

  • Need to remember to add () after a method call

  • defaults to auth user if no to: method
  • discussion on lexical scope

Counter_cache

  • In the model -> belongs_to :project, :counter_cache => true
  • railscast #23

Jquery

  • $("div,p,span") this works as a multiple selector
  • hidden divs

Selecting a winner

Migrate test db

  • ake db:migrate RAILS_ENV=test

No merge message for a no-ff flag

  • --no-edit

FB app auto-grow

Gem from a git url

  • gem 'redcarpet', :git => 'git://github.com/tanoku/redcarpet.git'

With an options hash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def facepile(*options)
opts = {:href => ENV['FACEBOOK_APP_URL'],
        :max_rows => 1,
        :width => 300,
        :show_count => true }
opts.merge!(options.first) unless options.empty?

raise "Must provide a :url option parameter or ENV['FACEBOOK_APP_URL']" unless opts[:href]

%Q{
<div class="fb-facepile" 
data-href="#{opts[:href]}" 
data-max-rows="#{opts[:max_rows]}"
data-show-count="#{opts[:show_count]}"
data-width="#{opts[:width]}">
</div>
}.html_safe
  end

FB invite friends

in coffeescript
1
2
3
4
5
6
7
inviteFriend: ->
  obj =
    method: 'apprequests',
    message: 'Come check this out'

  FB.ui obj, ->
    alert 'invited'

Delpoy

  • rake deploy:staging and rake deploy:production