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(); 
}