Wednesday, 21 November 2012

android sdk on mac osx

so i started with this tutorial :

http://buildcontext.com/blog/2009/installing-android-sdk-browser-testing-mac-os-x

what you really want is here:

http://stackoverflow.com/a/7962765


If you are getting the error XML verification failed for https://dl-ssl.google.com/android/repository/repository.xml. Error: cvc-elt.1: Cannot find the declaration of element 'sdk:sdk- repository'. Failed to fetch URL
in mac os, then download android sdk (Mac OS X (intel) android-sdk_r15-macosx.zip) from http://developer.android.com/sdk/index.html. Unzip this package and copy this unzip package on your mac root directory (Macintosh HD) and rename this unzip package as android-sdk. Now open android-sdk->tools->android. The sdk update will start automatically. You dont need to install java 6. It is automatically installed in your mac os.

Monday, 19 November 2012

ruby regex expressions

While working with regex expression i found two values resources:


and this cheat sheet for regular expressions


Friday, 16 November 2012

a theoretical problem with rails models

so let's say you have model 1: Locations
and you have model 2: Phones

You can't have a Location without at least a Phone and vice versa. Now let's say you only need a Phone for certain Location. Like for example a Post Office needs a Phone. But a private home doesn't really need one. What do you do:

class Locations < ActiveRecord::Base
                    has_many: Phones
                   validates: phone, :presence => true, :if => Proc.new {|location| location.needs_phone?}

   
          class Phones < ActiveRecord
                     belongs_to: Locations



Now the real problem comes at the specs. Here is what i discovered you can do

factory :locations do 
                trait :phone do
                     phone { FactoryGirl.create(:phone, :location_id => self) }
                end

          factory :phones do
               associations :locations


What i usually discovered is that when people look for a particular solution for they're problem you usually need bits and peaces from other people code. Maybe it will help you in a similar situation. I do understand that there can be made an argument that the models weren't thought out correctly and there can be a million other better solution.

A similar solution is you can put an after :build and then create the phone there. Or you can create the location as one that doesn't need a phone and then add the phone and switch to a phone required location.

 

Monday, 12 November 2012

another rspec cheat list

http://cheat.errtheblog.com/s/rspec/

$ gem install rspec

RSPEC-RAILS
===========

  RAILS-3
  =======

    CONFIGURE THE GEMFILE
    ======================
    group :development, :test do
      gem "rspec-rails", "~> 2.0"
    end

    INSTALL THE BUNDLE
    ===============================
    $ bundle install

    BOOTSTRAP THE APP
    ================= 
    $ ./script/rails generate rspec:install
          create  .rspec
          create  spec
          create  spec/spec_helper.rb
          create  autotest
          create  autotest/discover.rb

  RAILS-2
  =======

    INSTALL
    =======
    $ gem install rspec-rails -v 1.3.3

    BOOTSTRAP THE APP
    =================
    $ ./script/generate rspec
        create  spec
        create  spec/spec_helper.rb
        create  spec/spec.opts
        create  previous_failures.txt
        create  script/spec_server
        create  script/spec

HOW TO USE
==========

  COMMAND LINE
  =============
rspec --color --format doc spec/widget_spec.rb

  RAILS 3 (RSPEC 2)
  =============
./rails/generate model User
rake -T spec # lists all rspec rake tasks
rake spec # run all specs
rake spec/models/mymodel_spec.rb # run a single spec file
rake spec/models/mymodel_spec.rb:27 # run a single example or group on line 27

  RAILS 2 (RSPEC 1)
  =============
./script/generate rspec_model User
rake -T spec # lists all rspec rake tasks
rake spec # run all specs
rake spec SPEC=spec/models/mymodel_spec.rb SPEC_OPTS="-e \"should do
something\"" #run a single spec



module UserSpecHelper
  def valid_user_attributes
    { :email => "joe@bloggs.com",
      :username => "joebloggs",
      :password => "abcdefg"}
  end
end


describe "A User (in general)" do
  include UserSpecHelper

  before(:each) do
    @user = User.new
  end

  it "should be invalid without a username" do
    pending "some other thing we depend on"
    @user.attributes = valid_user_attributes.except(:username)
    @user.should_not be_valid
    @user.should have(1).error_on(:username)
    @user.errors.on(:username).should == "is required"
    @user.username = "someusername"
    @user.should be_valid
  end
end

EXPECTATIONS
=====================
target.should satisfy {|arg| ...}
target.should_not satisfy {|arg| ...}

target.should equal <value>
target.should_not equal <value>

target.should be_close <value>, <tolerance>
target.should_not be_close <value>, <tolerance>

target.should be <value>
target.should_not be <value>

target.should predicate [optional args]
target.should be_predicate [optional args]
target.should_not predicate [optional args]
target.should_not be_predicate [optional args]

target.should be < 6
target.should == 5
target.should be_between(1, 10)
target.should_not == 'Samantha'

target.should match <regex>
target.should_not match <regex>

target.should be_an_instance_of <class>
target.should_not be_an_instance_of <class>

target.should be_a_kind_of <class>
target.should_not be_a_kind_of <class>

target.should respond_to <symbol>
target.should_not respond_to <symbol>

lambda {a_call}.should raise_error
lambda {a_call}.should raise_error(<exception> [, message])
lambda {a_call}.should_not raise_error
lambda {a_call}.should_not raise_error(<exception> [, message])
lambda {a_call}.should change(instance, method).from(number).to(number)

proc.should throw <symbol>
proc.should_not throw <symbol>

target.should include <object>
target.should_not include <object>

target.should have(<number>).things
target.should have_at_least(<number>).things
target.should have_at_most(<number>).things

target.should have(<number>).errors_on(:field)

expect { thing.approve! }.to change(thing, :status).
    from(Status::AWAITING_APPROVAL).
    to(Status::APPROVED)

expect { thing.destroy }.to change(Thing, :count).by(-1)

Mocks and Stubs
===============
user_mock = mock "User"
user_mock.should_receive(:authenticate).with("password").and_return(true)
user_mock.should_receive(:coffee).exactly(3).times.and_return(:americano)
user_mock.should_receive(:coffee).exactly(5).times.and_raise(NotEnoughCoffeeExcep
ion)

people_stub = mock "people"
people_stub.stub!(:each).and_yield(mock_user)
people_stub.stub!(:bad_method).and_raise(RuntimeError)

user_stub = mock_model("User", :id => 23, :username => "pat", :email =>
"pat@example.com")

my_instance.stub!(:msg).and_return(value)
MyClass.stub!(:msg).and_return(value)

Examples (in the real world)

Thursday, 8 November 2012

Validation is very useful in rails

http://guides.rubyonrails.org/active_record_validations_callbacks.html#validates_with

5.3 Using a Proc with :if and :unless

Finally, it’s possible to associate :if and :unless with a Proc object which will be called. Using aProc object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners.
class Account < ActiveRecord::Base
  validates :password, :confirmation => true,
    :unless => Proc.new { |a| a.password.blank? }
end

Factory Girl is awesome

When doing specs it's always good to setup factories of common models so you can save up time to write code.

http://arjanvandergaag.nl/blog/factory_girl_tips.html

Get the most out of FactoryGirl

1. Use traits for modular factories

Traits are reusable pieces of attribute definitions that you can mix and match into your factories. Traits are to factories what modules are to classes a much more natural and flexible way of sharing common behaviour.
For example, say you have a Post and a Page object that both have a publication date. You could use inheritance to create various combinations:
FactoryGirl.define do
  factory :post do
    title 'New post'

    factory :draft_post do
      published_at nil
    end

    factory :published_post do
      published_at Date.new(2012, 12, 3)
        end
      end

  factory :page do
    title 'New page'
    
    factory :draft_page do
      published_at nil
    end

    factory :published_page do
      published_at Date.new(2012, 12, 3)
    end
  end
end

FactoryGirl.create :draft_page
FactoryGirl.create :published_post

Tuesday, 6 November 2012

rails bang methods

I found this very interesting article on bang methods in rails:

http://dablog.rubypal.com/2007/8/15/bang-methods-or-danger-will-rubyist

What ! does (and does not) mean

The ! in method names that end with ! means, “This method is dangerous”—or, more precisely, this method is the “dangerous” version of an otherwise equivalent method, with the same name minus the !. “Danger” is relative; the ! doesn’t mean anything at all unless the method name it’s in corresponds to a similar but bang-less method name.
So, for example, gsub! is the dangerous version of gsubexit! is the dangerous version of exitflatten! is the dangerous version of flatten. And so forth.
The ! does not mean “This method changes its receiver.” A lot of “dangerous” methods do change their receivers. But some don’t. I repeat: ! does not mean that the method changes its receiver.

you can read the rest in the article

javascript default value for argument

If you want to pass an argument with a default value in javascript this is how you do it.
http://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function


function foo(a, b)
 {
   a = typeof a !== 'undefined' ? a : 42;
   b = typeof b !== 'undefined' ? b : 'default_b';
   ...
 }

Monday, 5 November 2012

how to comunicate if the internet is down for good

just a shout out for this very interesting article:

http://12160.info/profiles/blogs/how-to-communicate-if-the-government-obliterates-the-internet

and in case you want to read more:

http://www.reddit.com/r/darknetplan/

Thursday, 1 November 2012

rails generate add column to table

this is something i keep forgetting so up it goes :)

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

rails generate migration add_fieldname_to_tablename fieldname:string
This will generate the file timestamp_add_fieldname_to_tablename, which will look like this:
class AddFieldnameToTablename < ActiveRecord::Migration
  def up
    add_column :tablenames, :fieldname, :string
  end

  def down
    remove_column :tablenames, :fieldname
  end
end

some javascript interesting stuff

This is a few interesting javascript stuff:

1)  javscript namespace declaration:

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();

2) javascript test if function is defined:
    http://www.idealog.us/2007/02/check_if_a_java.html

if(typeof yourFunctionName == 'function') { 
yourFunctionName(); 
} 

Monday, 29 October 2012

How to make an alias in the terminal on mac osx

Credits to:

http://highervisibilitywebsites.com/how-make-terminal-alias-mac-os-x

After looking around for how to make an alias for Mac OS X's terminal/shell I ended up cobbling together my solution from a variety of different (mostly unixy-linuxy) places. So in the name of good documentation, here is the magic formula for the next time I need to set up an alias for happier command line hacking:
  1. First we edit/create a profile. For a normal user do:
    pico /etc/profle
    ...or for root/superuser do:
    pico ~/.profile
  2. Add your alias like so to the file:
    alias aliasname='mycommand /path/path'
    (notice no space between equal sign and ')
  3. Save your changes and close the file
  4. Load/reload your profile with:
    . /etc/profile
    ...or for root/superuser do:
    . ~/.profile
  5. If you are using root/sudo you will need to use sudo -i in order to load the profile upon login (more info about this here).
  6. Done.

highlight effect without jquery-ui

So i recently had to do a highlight effect without the use of jquery-ui. Something like this:
http://docs.jquery.com/UI/Effects/Highlight

jQuery.fn.highlight = function(level) {

  highlightIn = function(options){

    var el = options.el;
    var visible = options.visible !== undefined ? options.visible : true;

    setTimeout(function(){
      if (visible) {
        el.css('background-color', 'rgba('+[255, 64, 64]+','+options.iteration/10+')');
        if (options.iteration/10 < 1) {
          options.iteration += 2;
          highlightIn(options);
        }
      } else {
        el.css('background-color', 'rgba('+[255, 64, 64]+','+options.iteration/10+')');
        if (options.iteration/10 > 0) {
          options.iteration -= 2;
          highlightIn(options);
        } else {
          el.css('background-color', '#fff');
        }
      }
    }, 50);
  };

  highlightOut = function(options) {
    options.visible = false;
    highlightIn(options);
  };

  level = typeof level !== 'undefined' ? level : 'warning';
  highlightIn({'iteration': 1, 'el': $(this), 'color': level});
  highlightOut({'iteration': 10, 'el': $(this), 'color': level});
};

Friday, 26 October 2012

rails debugger

So i recently discovered a debugger for ruby on rails. Since i've been using emacs there isn't a lot of options. Luckily we have the debugger gem which is very useful:

CREDITS TO:

http://www.intridea.com/blog/2010/12/7/debug_rails_application_with_ruby-debug

I worked with GNU C/C++ for a long time before I met Ruby. The two languages are very different; they have their own strengths and weaknesses in different application scenarios. But there is one nice thing that they have in common: they both have great debuggers for their developers who are hitting their heads on their keyboards trying to find out what has gone wrong with their applications.
My associate, Yong Zhi, wrote a great blog post on how to debug a Ruby application, a standalone script, or a full-stacked Rails application with GDB, GNU Project Debugger. Within the Ruby community there is always more than one option you can choose from. As many of you know, ruby-debugprovides almost the same directives with GDB, so, for the Ruby developers who have used GDB before, there will not be a steep learning curve. What I want to share with you today is how I make my life easier with help from ruby-debug.
The following steps are used to get ruby-debug working with a Rails 3 application.
Step 1: Install ruby-debug
Open Gemfile, add the following lines to it:
group :development do
  gem 'ruby-debug'
end
and run bundle install to install the gem.
Step 2: Start the server for development
rails server --debugger
Step 3: Find the bug
For the line you where you want to setup a breakpoint, just place a 'debugger', whether it's in a view, a controller or a model.
# in a view file new.html.erb
<%= content_for_the_main %>
<% debugger %>
<%= content_for_the_side_column %>

# in a controller file, posts_controller.rb
class PostsController &lt; ApplicationController
  ...

  def new
    debugger
    post = current_user.posts.new
  end

  ...
end

# in a model file, post.rb
class Post &lt; ActiveRecord::Base
  ...

  def self.funny_ones
    debugger
    self.where(:funny => false)
  end

  ...
end
Send another request after setting up the breakpoints; the server will stop at the first breakpoint it runs into, waiting for the further instructions:
(rdb:1)
With the prompt, you can get a list of directives with "help", or "help backtrace" for the usage of specific directive. Usually, I'll use 'l', short for 'list', to take a look at where the application stops:
(rdb:1) l
22    def new
23      debugger
=> 24      post = current_user.posts.new(params[:post])
After that, check out the value of the variable with 'p', short for 'print',
(rdb:1) p params.inspect
After that, you can continue to the next line with 'n', short for 'next',
(rdb:1) n
Or, you can use 'c', short for 'continue', to get to the next breakpoint. If there are not any breakpoints left, the reponse will be sent back to the client and the request-response loop is over.
(rdb:1) c
If you want to know how you got where you are, just call 'bt', short for 'backtrace',(rdb:1) bt
--> #0 TabsController.edit 
      at line /home/hao/Sandbox/demo/app/controllers/posts_controller.rb:24
    #1 Kernel.send_action 
      at line /home/hao/.rvm/gems/ree-1.8.7-2010.02@demo/gems/actionpack-3.0.0/lib/action_controller/metal/implicit_render.rb:4
    #2 ActionController::ImplicitRender.send_action 
      at line /home/hao/.rvm/gems/ree-1.8.7-2010.02@demo/gems/actionpack-3.0.0/lib/action_controller/metal/implicit_render.rb:4
    #3 AbstractController::Base.process_action(method_name#String) 
      at line /home/hao/.rvm/gems/ree-1.8.7-2010.02@demo/gems/actionpack-3.0.0/lib/abstract_controller/base.rb:150
If you want to step into a function call you may have interest in, you can call 's', short for 'step',
(rdb:1) s
To step out of the function call you just stepped into, use 'fin', short for 'finish',
(rdb:1) fin
To quit the debugger, type 'q', short for 'quit',
(rdb:1) q
Those are most of the ruby-debug directives that I find myself using daily. There's one more feature of ruby-debug that can bring great help for the debugging: irb session.
(rdb:1) irb
You can open as many irb sessions as you want, you can change the value of the variable to try it out.
ree-1.8.7-2010.02 > params[:post] = {:title => "Hello, world!", :body => "Hello, world, again!"}
ree-1.8.7-2010.02 > exit
(rdb:1) c 


Thursday, 25 October 2012

jquery select element by the href link

I use this quite often. how to select an link element using the href link:

http://stackoverflow.com/questions/303956/jquery-select-a-which-href-contains-some-string

$('a[href$="ABC"]')...

Yap that's it.

Thursday, 6 September 2012

emacs key bindings

always useful:

CREDIT TO:

http://wttools.sourceforge.net/emacs-stuff/emacs-keybindings.html

Wednesday, 5 September 2012

`start_tcp_server': no acceptor (Runtime Error)

CREDIT TO:

http://stackoverflow.com/questions/9605430/thin-web-server-start-tcp-server-no-acceptor-runtimeerror-after-git-branch

this seem to work for me:

This works for me. Find (zombie?) server (can happen when quitting terminal with server running):
$ ps ax | grep rails
If it returns something like:
33467 s002 S+ 0:00.00 grep rails33240 s003 S+ 0:15.05 /Users/Arta/.rbenv/versions/1.9.2-p290/bin/ruby script/rails s -p 3000
kill it, and run anew:
$ kill -9 33240
$ rails s