Archive for the ‘Uncategorized’ Category

Using route to fuck gfw!

Posted: March 16, 2011 in GFW, Uncategorized
Tags: ,

You can use route command to smart your vpn traffic.

add some rules to your pptp /etc/ppp/ip-up:

#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"

LOCALGATEWAY=`netstat -nr | grep '^default' | grep -v 'ppp' | sed 's/default *([0-9.]*) .*/1/'`


if [ ! -e /tmp/pptp_localgateway ]; then
    echo "${LOCALGATEWAY}" > /tmp/pptp_localgateway
fi

dscacheutil -flushcache


route add 1.12.0/14 "${LOCALGATEWAY}"
route add 1.24.0/13 "${LOCALGATEWAY}"
route add 1.45.0/16 "${LOCALGATEWAY}"

and /etc/ppp/ip-down:

#!/bin/sh
export PATH="/bin:/sbin:/usr/sbin:/usr/bin"


if [ ! -e /tmp/pptp_localgateway ]; then
        exit 0
fi

LOCALGATEWAY=`cat /tmp/pptp_localgateway`


route delete 1.12.0/14 ${LOCALGATEWAY}
route delete 1.24.0/13 ${LOCALGATEWAY}
route delete 1.45.0/16 ${LOCALGATEWAY}
route delete 1.48.0/14 ${LOCALGATEWAY}

rm /tmp/pptp_localgateway

Notice: Do not forget to add 192.168.0/16 to your local gateway(maybe eth0, ppp0 for vpn gateway)

ipv4list

http://www.dustindiaz.com/klass/

Just some notes after reading “Eloquent Ruby” chapter one.

indent

use two spaces per indent

comments

There are good reasons for adding comments to your code, the best being to explain how to use your software masterpiece. These kinds of “how to” comments should focus on exactly that: how to use the thing. Don’t explain why you wrote it, the algorithm that it uses, or how you got it to run faster than fast. Just tell me how to use the thing and remember that examples are always welcome.

Sometimes it’s also wise to include a “how it works” explanation of particularly complicated bits of code. Again, keep this kind of explanation separate from the “how to”.

The occasional in-line comment can also help.

Remember, good code is like a good joke: It needs no explanation.

Camels for Classes, Snakes Everywhere Else

  • Almost everything in this context means methods, arguments, and variables, including instance variables use snake case.
  • Class names are camel case.
  • Constants use all uppercase, punctuated by underscores.

Parenthess

both in method definitions and calls surround parenthess.

don’t surround parenthess:

  • conditions in control statements
  • defining or calling a method with no parameters
  • puts, instance_of?, and your right feeling

Look set.rb in your ruby lib path for more ruby conventions.

Naming

  • end the name of a method that answers a yes/no or true/false question with a question mark
  • reserve ! to adorn the names of methods that do something unexpected, or perhaps a bit dangerous

Extending Rails with Plugins

Posted: March 12, 2011 in Uncategorized

Just some notes after reading “The Rails3 Way” chapter nineteen.

init your plugin

==> rails g plugin my_plugin
      create  vendor/plugins/my_plugin
      create  vendor/plugins/my_plugin/MIT-LICENSE
      create  vendor/plugins/my_plugin/README
      create  vendor/plugins/my_plugin/Rakefile
      create  vendor/plugins/my_plugin/init.rb
      create  vendor/plugins/my_plugin/install.rb
      create  vendor/plugins/my_plugin/uninstall.rb
      create  vendor/plugins/my_plugin/lib
      create  vendor/plugins/my_plugin/lib/my_plugin.rb
       error  rspec [not found]

bug: need rspec:plugin generator

Code that’s added to init.rb is run at startup. (That’s any sort of Rails commands, including server, console, and runner.) Most plugins have their require statements in init.rb.

The lib directory of your plugin is added to Ruby’s load path before init.rb is run.

In addition to opening existing classes to add or modify behavior, there are at least three other ways used by plugins to extend Rails functionality:

  • Mixins, which describes inclusion of modules into existing classes
  • Dynamic extension through Ruby’s callbacks and hooks such as method_missing, const_missing, and included
  • Dynamic extension through Ruby’s callbacks and hooks such as method_missing, const_missing, and included Dynamic extension using runtime evaluation with methods such as eval, class_eval, and instance_eval

Most plugins follow a pattern used internally in Rails and split their methods into two modules, one each for class and instance methods.

vendor/plugins/my_plugin/lib/my_plugin.rb

# MyPlugin
#class ActiveRecord::Base 
  #def self.[](id)
    #find(id)
  #end
#end

module MyPlugin
  extend ActiveSupport::Concern

  #extending ActiveSupport::Concern automatically does the following 
  #def self.included(base)
  #base.extend(ClassMethods)
  #base.send(:include, InstanceMethods)
  #end

  module ClassMethods 

    def [](id)
      find(id) 
    end

  end

  module InstanceMethods 

    def to_param
      has_name? ? "#{id}-#{name.gsub(/[^a-z0-9]+/i, '-')}" : super
    end

    private

    def has_name?
      respond_to?(:name) and persisted?
    end

  end

end

vendor/plugins/my_plugin/init.rb

# Include hook code here
#puts "Current Rails version: #{Rails::VERSION::STRING}"
require 'my_plugin'

ActiveRecord::Base.send(:include, MyPlugin)
#ActiveRecord::Base.class_eval do 
  #include MyPlugin
#end

My previous entry Ruby’s Object Model maybe useful if you want to become a master of Ruby.

vendor/plugins/my_plugin/install.rb

  • Copying asset files (HTML, CSS, and so on) into the public directory
  • Checking for the existence of dependencies (for example, RMagick)
  • Installing other requisite plugins
  • Displaying documentation

The rails plugin remove command checks for the presence of a file called uninstall.rb when removing a plugin. I

If as a plugin writer you are concerned about making sure that your install and/or uninstall scripts are actually executed, it’s probably worthwile to stress the point in your announcements to the community and within the plugin documentation itself, such as the README file.

For javascript, you will simply need to register a javascript expansion using ActionView::Helpers::AssetTagHelper. In the following example we add two javascript files from our plugin under the namespace my_plugin. Note that the source files in the plugin must also reside in public/javascripts.

ActionView::Helpers::AssetTagHelper.register_javascript_expansion :my_plugin => ["core", "ext"]

This javascript can then be loaded into the application through the standard javascript include tag, and passing the name defined by the plugin.

javascript_include_tag :my_plugin

Railties

Railties are classes that extend from Rails::Railtie and provide hooks into Rails ini- tialization for add-on libraries. This is extremely useful for gems which want to seemlessly integrate with Rails.

Railties provide hooks for libraries to add the following functionality:

  • Creating initializers
  • Providing Rake tasks
  • Adding generators
  • Registering event subscribers (for logging)

To create a Railtie, create a class called Railtie in your project’s namespace that inherits from Rails::Railtie. Make sure you require ‘rails’ and your own gem in the file as well.

require 'my_gem' 
require 'rails'
module MyGem
  class Railtie < Rails::Railtie

    initializer "setup" do 
      # Some initialization code here, like setting up a 
      # database connection.
    end

    initializer "verify setup" do
      config.after_initialize do
        # Do some verification on the setup.
      end
    end

    rake_tasks do
      load 'my_gem/railties/tasks.rake'
    end

    generators do 
      require 'my_gem/rails/generators/my_generator'
    end

    log_subscriber :my_gem, MyGem::Railtie::Subscriber.new

  end
end

More about Railtie

Active View

Posted: March 9, 2011 in Uncategorized

Just some notes after reading “The Rails3 Way” chapter ten.

Wonderful Haml

Sharing state via instance variables in controllers promotes close coupling with views. decent_exposure gives you a declarative manner of exposing an interface to the state that controllers contain, thereby decreasing coupling and improving your testability and overall design.

%div{:class => page_class} My Div

Whenever you want to send the user a message from the controller layer, but only for the duration of the next request, use flash.

A common Rails practice is to use flash[:notice] to hold benign notice messages, and flash[:alert] for communication of a more serious nature.

Sometimes you want to give the user a flash message, but only for the current request. In fact, a common newbie Rails programming mistake is to set a flash notice and not redirect, thereby incorrectly showing a flash message on the following request.
It is possible to make flash cooperate with a render by using the flash.now method.

:partial => 'entry', :collection => entries

= div_for(entry) do 
  #{entry_counter}:#{entry.description} 
  #{distance_of_time_in_words_to_now entry.created_at} ago

entries should not be an array of numbers, other than you will get undefined methodmodel_name’ for Fixnum:Class`

Untitled

Posted: March 9, 2011 in Uncategorized

http://pleac.sourceforge.net/pleac_ruby/

If your Firefox browser suddenly does not open after updating it, then most likely your Profiles folder has been corrupted.

/Applications/Firefox.app/Contents/MacOS/firefox-bin -ProfileManager

Create new profile

Active Record Associations

Posted: March 8, 2011 in Uncategorized

Just some notes after reading “The Rails3 Way” chapter seven.

Media_httpmediatumblr_dbcsn

class AssociationProxy #:nodoc:
  alias_method :proxy_respond_to?, :respond_to?
  alias_method :proxy_extend, :extend
  delegate :to_param, :to => :proxy_target
  instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil?|send|object_id|to_a)$|^__|^respond_to_missing|proxy_/ }

  def initialize(owner, reflection)
    @owner, @reflection = owner, reflection
    @updated = false
    reflection.check_validity!
    Array.wrap(reflection.options[:extend]).each { |ext| proxy_extend(ext) }
    reset
  end

  # Returns the owner of the proxy.
  def proxy_owner
    @owner
  end

You can prove that timesheet is actually a proxy by asking it if it responds to one of AssociationProxy’s public methods, such as proxy_owner:

>> obie.timesheets.respond_to? :proxy_owner
=> true

«(*records) and create(attributes = {}) Both methods will add either a single associated object or many, depending on whether you pass them an array or not. However, « is transactional, and create is not.
Yet another difference has to do with association callbacks (covered in this chapter’s options section for has_many). The « method triggers the :before_add and :after_add callbacks, but the create method does not.
Finally, the return value behavior of both methods varies wildly. The create method returns the new instance created, which is what you’d expect given its counterpart in ActiveRecord::Base. The « method returns the association proxy (ever masquerad- ing as an array), which allows chaining and is also natural behavior for a Ruby array.
However, « will return false and not itself if any of the records being added causes the operation to fail. You shouldn’t depend on the return value of « being an array that you can continue operating on in a chained fashion.

force reload:

ruby-1.9.2-p136 > u = Post.first
 => #<Post id: 1, content: nil, user_id: 1, slug: nil, created_at: "2011-03-07 08:27:00", updated_at: "2011-03-07 08:27:00", title: nil, body: nil, published: nil>
ruby-1.9.2-p136 > u.user.object_id
 => 2186758280 
ruby-1.9.2-p136 > u.user.object_id
 => 2186758280 
ruby-1.9.2-p136 > u.user(true).object_id
 => 2164737540 
ruby-1.9.2-p136 > u.user(true).object_id
 => 2169019120

:conditions on relationships never affect the assignment of associated objects, only how they’re read back from the database.

Active Record Migrations

Posted: March 7, 2011 in Uncategorized

Just some notes after reading “The Rails3 Way” chapter six.

Note that if you change the classname of your migration to something that doesn’t match its filename, you will get an uninitialized constant error when that migration gets executed.

Migrations that have already been run are listed in a special database table that Rails maintains. It is named schema_migrations and only has one column, version.

When you pull down new migrations from source control, rake db:migrate will check the schema_migrations table and execute all migrations that have not yet run (even if they have earlier timestamps than migrations that you’ve added yourself in the interim).

Transformations that cannot be reversed should raise an ActiveRecord::IrreversibleMigration exception in their down method.

def self.up
  # Phone number fields are not integers, duh!
  change_column :clients, :phone, :string
end
def self.down 
  raise ActiveRecord::IrreversibleMigration
end

To execute a rollback, use the migrate task, but pass it a version number to rollback to, as in rake db:migrate VERSION=20090124223305.

Custom default id

create_table :posts, :id => false  do |t|
  t.text :content
  t.integer :user_id
  t.text :slug

  t.timestamps
end

or

create_table :posts, :id => :xxx_id do |t|
  t.text :content
  t.integer :user_id
  t.text :slug

  t.timestamps
end

The automatically created file db/seeds.rb is a default location for creating seed data for your database. It was introduced in order to stop the practice of inserting seed data in individual migration files, if you accept the premise that migrations should never be used for seeding example or base data required by your application. It is executed with the rake db:seed task (or created alongside the database when you run rake db:setup).

Migrations in rubyonrails guide

my rails3 app template

Posted: March 6, 2011 in Uncategorized

https://github.com/hujinpu/railstemplate

Rails3’s generator api
depend on thor’s action