2016年3月30日 星期三

Stubs, Mocks, and Spies

stubs:
create fake object, and assume this fake object can response what information, response, make sure the main tested object can get the consistent result

mocks
same with stubs, but must be executed




 from https://danielzhangqinglong.github.io/2015/04/07/rspec-mock/

比如說, 現在要去測試一下Twitter是不是成功發了一條推文:
1
2
3
4
5
6
7
8
9
10
require 'twitter'
class TwitterEmotion
def tweet
twitter_client.update "I am very happy"
end
def twitter_client
Twitter::REST::Client .new
end
end
測試代碼:
1
2
3
4
it "should tweet successfully" do
emotion = TwitterEmotion. new
expect{ emotion.tweet }.not_to raise_error
end
但是這真的會把你的推文發生出去,還有,如果網絡環境不好或者Twitter的服務器沒有及時處理請求,那麼我這邊的測試就會跑不通,等等問題. 
正因為如此,才需要把使用Twitter服務的部分用mock代替.這樣測試就不會和Twitter進行交互了.下面是使用mock後的測試:
1
2
3
4
5
6
7
8
9
10
11
12
it "should tweet successfully" do
# mock Twitter client
twitter_client_mock = double( 'Twitter client' )
# 讓update方法可以在mock對像上調用
allow(twitter_client_mock). to receive(:update)
emotion = TwitterEmotion. new
allow(emotion). to receive(:twitter_client).and_return(twitter_client_mock)
# 如果在emotion上調用了twitter_client, 那麼就返回twitter_client_mock
expect{ emotion.tweet }.not_to raise_error
end



allow (想要替換方法的對象) . to receive (所要替換的方法) . and_return (返回值對象)


allow
(mock對象) . to receive (方法) . and_raise (異常)

Initialize the serializer

ActiveModel::ArraySerializer.new(Funding.all, each_serializer: FundingSerializer).to_json




For me I passed the view_context to the array serializer:
ActiveModel::ArraySerializer.new(your_array, each_serializer: YourSerializer, scope: self.view_context)

how to pass scope

https://github.com/rails-api/active_model_serializers/issues/510




2016年3月3日 星期四

好的架構源於不停地衍變

架構的演進


http://www.csdn.net/article/2015-10-24/2826028

所有東西在一台機器上








資料庫變成瓶頸
改成分佈式架構



將業務層 資料庫層 在做垂直的拆分 減輕壓力




多一個服務層 來較用呼叫其他方法

2016年3月2日 星期三

Why I No Longer Use MVC Frameworks 



 In traditional MVC, the action (controller) would call an update method on the model and upon success (or error) decide how to update the view


The SAM pattern can be represented by the following expression:
         V = S( vm( M.present( A(data) ) ), nap(M))
which stipulates that the view V of a system can be computed, after an action A has been applied, as a pure function of the model.

In SAM, A (actions), vm (view-model), nap (next-action predicate) and S (state representation) are and must all be pure functions. With SAM, what we commonly call the “state” (the values of the properties of the system) is entirely confined to the model and the logic that changes these values is not visible outside the model itself. 







The SAM pattern changes completely the paradigm of front-end architectures because, on the foundation of TLA+, the business logic can be clearly delineated into:
  • Actions as pure functions
  • CRUD operations in the model
  • States which control automatic Actions

2016年2月27日 星期六

Making Generators in Rails 


class LayoutGenerator < Rails::Generators::Base
  source_root File.expand_path('../templates', __FILE__)
  argument :layout_name, :type => :string, :default => "application"
  class_option :stylesheet, :type => :boolean, :default => true, :description => "Include stylesheet file"

  def generate_layout
    copy_file "stylesheet.css", "public/stylesheets/#{file_name}.css" if options.stylesheet?
    template "layout.html.erb", "app/views/layouts/#{file_name}.html.erb"
  end

  private
  def file_name
    layout_name.underscore
  end

end

every public method in the class (Rails::Generators::Base) will be executed when the generator runs

  • arguments optional:  we can define a default value for each argument. We’ll add a layout_name argument with a default value of application
  • template method: which takes similar arguments to copy_file but which will parse any erb in the template before copying it to the destination directory
  • class_option: the ability to pass an option that will stop the stylesheet file being generated. We can do this by using the class_option method







Rebuilding Rails

 1. Zero to “It Works!”
     Just describe the basic gem, and how to use it

     ActiveSupport: some utils like single to plural, time and date support
     ActiveModel: thin wrapper around many different ActiveModel implementations to tell Rails how to use them
     ActiveRecord: ORM
     ActionPack: routing, request through controller, action, render to view
     ActionMailer: email

  1. http code: 303 redirect

router的作法, 由rack的env來 找出controller和action
  1. autoloading
用to_underscore來找出所要呼叫的controller
再用const_missing和const_get來自動require

  1. Rendering Views
render: 先找出view的檔案 filename = File.join 'app', 'views', controller_name, "#{view_name}.html.erb"
     def controller_name
           klass = self.class
           klass = klass.to_s.gsub /Controller$/, ''
           Rulers.to_underscore klass
     end

想從controller傳instance variable到view時需要用到instance_variables和instance_variable_get來倒到view
eruby.result locals.merge(:env => env).merge(view_assigns).merge(other_settings)
    def view_assigns
      hash = {}
      variables = instance_variables
      variables -= [:@env]
      variables.each { |name| hash[name] = instance_variable_get(name) }
      hash
    end

     5. Basic Models
like ActiveRecord
find, all, create, update …..
Exercise 2,3 沒做

     6. Request, Response
using Rackʼs Request and Response objects
Exercise 沒做


     7
     8. Rack Middleware

use ‘use’ add layer by layer 

2016年2月18日 星期四

Reading Rails - Concern 


major feature:
  1. auto extend ClassMethods and included InstanceMethods
  2. Dependency resolution

  • Included

Module defines the callback included which is called when a module is included into another class or module

if both two module are extend ActiveSupport::Concern, and both have included do 
module Named
  extendActiveSupport::Concern
  included do
     base.validates_presence_of:first_name,:last_name
  end#...
end

module Mailable
  extendActiveSupport::Concern
  include Named
  included do
     email_regexp =/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/base.validates_format_of:email,with:email_regexp
  end#...
end


Concern delays calling these blocks until your module is included in something that is not a Concern.

  • Class Methods

Calling include only mixes in the instance methods

If there is a ClassMethods module in a Concern, it will automatically extend whatever it is included in.
module Exclaimable
     def self.included(base)
          base.extend(ClassMethods)
     end
     module ClassMethods
          def shout!
               puts"Look out!"
          end
     end
end


  • How It Works

module ActiveSupport
  module Concern
    def self.extended(base)
      base.instance_variable_set("@_dependencies", [])
    end

    def append_features(base)
      if base.instance_variable_defined?("@_dependencies")
        base.instance_variable_get("@_dependencies") << self
        return false
      else
        return false if base < self
        @_dependencies.each { |dep| base.send(:include, dep) }
        super
        base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
        base.send :include, const_get("InstanceMethods") if const_defined?("InstanceMethods")
        base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
      end
    end

    def included(base = nil, &block)
      if base.nil?
        @_included_block = block
      else
        super
      end
    end
  end
end

Concern delays calling included blocks and mixing in ClassMethods by keeping track of modules in @_dependencies. When a Concern is included in another class, it triggers all the logic on that class.

While unpacking how Concern works, we also came across some other interesting things:
  • Module defines included and extended callbacks.
  • Ruby provides methods such as instance_method_get to access an object's internals.
  • Class methods are not mixed in with include.
  • include takes any number of arguments: include ModA, ModB, ModC.
  • Classes can be compared with equality operations: ClassA < ClassB.
  • By convention, anything starting with a capital letter is a constant.