王筝的博客
ruby学习

$sudo dpkg -i alilang.deb

$ sudo alilang

 

使用 callback 确保创建,更新和删除 Picture 时,touch 关联的 imageable,使得其缓存能正确过期

这个update的方法用来把update时间强制更新成当前时间

http://guides.rubyonrails.org/association_basics.html

4.1.2.9 :touch

If you set the :touch option to true, then the updated_at or updated_on timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:

class Book < ApplicationRecord
  belongs_to :author, touch: true
end
 
class Author < ApplicationRecord
  has_many :books
end

由于在多态关联中直接写touch :true没有起作用,写了另一个方法

class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true                             
                                                                       
  validates_uniqueness_of :name, scope: [:imageable_id, :imageable_type]
                                                                       
  after_save :touch_imagable
  after_destroy :touch_imagable
                                                                       
  def touch_imagable
    imageable.touch                                                    
  end                                                                  
end  

 

 

https://github.com/rails/jbuilder  的set!方法重构接口,

因为grape没法使用 jBuilder 的缓存,所以直接用 Rails 写 API

(1)多个图片

images: {
  poster: {
    url: "http://r4.ykimg.com/0510000057CD17166714C04FDC0628CE",
    md5: "ee63b0a11cb1e39331d5ce11d38fceec"
},
  right_top_corner: {
    url: "http://r1.ykimg.com/0510000057CEA19C6714C063660BEB44",
    md5: "e50d520de494538d4633086d46845a81"
  }
},

原来的方法为

 json.images do
    component.pictures.each do |p|
      if p.name == 'poster'
        json.poster do
          json.url "http://r#{rand(4) + 1}.xxx.com/#{p.url}"
          json.md5 p.md5
        end
      end
      if p.name == 'icon'
        json.icon do
          json.url "http://r#{rand(4) + 1}.xxx.com/#{p.url}"
          json.md5 p.md5
        end
      end
      if p.name == 'background'
        json.background do
          json.url "http://r#{rand(4) + 1}.xxx.com/#{p.url}"
          json.md5 p.md5
        end
      end
  end 
end

精简后为

  json.images do
    component.pictures.each do |p| 
      json.set! p.name do
        json.set! :url, "http://r#{rand(4) + 1}.ykimg.com/#{p.url}"
        json.set! :md5, p.md5
      end 
    end 
  end 

(2)hints 是一个 hash,遍历 Hash 的文档 http://ruby-doc.org/core-2.3.1/Hash.html#method-i-each

hint: {
  left: "left",
  right: "111"
},

精简前

  json.hint do
    if component.hints.key?("left")
      json.left component.hints["left"]
    end 
    if component.hints.key?("center")
      json.center component.hints["center"]
    end 
    if component.hints.key?("right")
      json.right component.hints["right"]
    end 
  end

精简后

  json.hint do
    component.hints.each do |key,value|
      json.set! key, value
    end
  end

 

 

(1)Download IntelliJ IDEA

https://www.jetbrains.com/idea/download/

 

(2)找了个激活码

http://www.oschina.net/code/snippet_2303434_57174

 

43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QTczWVlKIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiIiwiYXNzaWduZWVFbWFpbCI6IiIsImxpY2Vuc2VSZXN0cmljdGlvbiI6IkZvciBlZHVjYXRpb25hbCB1c2Ugb25seSIsImNoZWNrQ29uY3VycmVudFVzZSI6ZmFsc2UsInByb2R1Y3RzIjpbeyJjb2RlIjoiSUkiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJBQyIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IkRQTiIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlBTIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiRE0iLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJDTCIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlJTMCIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IlJDIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0seyJjb2RlIjoiUEMiLCJwYWlkVXBUbyI6IjIwMTctMDItMjUifSx7ImNvZGUiOiJSTSIsInBhaWRVcFRvIjoiMjAxNy0wMi0yNSJ9LHsiY29kZSI6IldTIiwicGFpZFVwVG8iOiIyMDE3LTAyLTI1In0sey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GJxFjnye8NT1PAywoyl7RmiAVRE/EKwIDAQABo4GZMIGWMAkGA1UdEwQCMAAwHQYDVR0OBBYEFGEpG9oZGcfLMGNBkY7SgHiMGgTcMEgGA1UdIwRBMD+AFKOetkhnQhI2Qb1t4Lm0oFKLl/GzoRykGjAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBggkA0myxg7KDeeEwEwYDVR0lBAwwCgYIKwYBBQUHAwEwCwYDVR0PBAQDAgWgMA0GCSqGSIb3DQEBCwUAA4ICAQC9WZuYgQedSuOc5TOUSrRigMw4/+wuC5EtZBfvdl4HT/8vzMW/oUlIP4YCvA0XKyBaCJ2iX+ZCDKoPfiYXiaSiH+HxAPV6J79vvouxKrWg2XV6ShFtPLP+0gPdGq3x9R3+kJbmAm8w+FOdlWqAfJrLvpzMGNeDU14YGXiZ9bVzmIQbwrBA+c/F4tlK/DV07dsNExihqFoibnqDiVNTGombaU2dDup2gwKdL81ua8EIcGNExHe82kjF4zwfadHk3bQVvbfdAwxcDy4xBjs3L4raPLU3yenSzr/OEur1+jfOxnQSmEcMXKXgrAQ9U55gwjcOFKrgOxEdek/Sk1VfOjvS+nuM4eyEruFMfaZHzoQiuw4IqgGc45ohFH0UUyjYcuFxxDSU9lMCv8qdHKm+wnPRb0l9l5vXsCBDuhAGYD6ss+Ga+aDY6f/qXZuUCEUOH3QUNbbCUlviSz6+GiRnt1kA9N2Qachl+2yBfaqUqr8h7Z2gsx5LcIf5kYNsqJ0GavXTVyWh7PYiKX4bs354ZQLUwwa/cG++2+wNWP+HtBhVxMRNTdVhSm38AknZlD+PTAsWGu9GyLmhti2EnVwGybSD2Dxmhxk3IPCkhKAK+pl0eWYGZWG3tJ9mZ7SowcXLWDFAk0lRJnKGFMTggrWjV8GYpw5bq23VmIqqDLgkNzuoog==

 

 

(3)select project SDK, 选择JDK

 

(4)java select  directory is not a valid home for jdk

因为还没装jdk,下载地址为

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

我选择的是mac版本的

(5) 下载tomcat, 我下载的是后缀名为tar.gz的这个

http://tomcat.apache.org/download-80.cgi#8.5.5

 

(6)把tomcat移动到/Library里并修改权限、启动

 

$ cd /Library/
$ sudo mv ~/Downloads/apache-tomcat-8.5.5 .
$ sudo mv apache-tomcat-8.5.5/   Tomcat/
$ sudo chmod 755 /Library/Tomcat/bin/*.sh
$ cd Tomcat/
$ cd bin
$  ./startup.sh 

查看日志

$ cd ../logs/
$ tail -500 catalina.out

这时候可以查看下localhost:8080看下效果

 

 

最近在处理一个小功能,每个元素可以有多个图片,每个图片的name表示了它是背景图还是海报图,

需要对每个元素的图片name做一个唯一性验证,一个元素不能添加两个海报图,

使用的是validates_uniqueness_of

 

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of

Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user can be named “davidhh”.

class Person < ActiveRecord::Base
  validates_uniqueness_of :user_name
end

It can also validate whether the value of the specified attributes are unique based on a :scope parameter:

class Person < ActiveRecord::Base
  validates_uniqueness_of :user_name, scope: :account_id
end

Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
end

It is also possible to limit the uniqueness constraint to a set of records matching certain conditions. In this example archived articles are not being taken into consideration when validating uniqueness of the title attribute:

class Article < ActiveRecord::Base
  validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') }
end

When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.

Configuration options:

  • :message – Specifies a custom error message (default is: “has already been taken”).
  • :scope – One or more columns by which to limit the scope of the uniqueness constraint.
  • :conditions – Specify the conditions to be included as a WHERE SQL fragment to limit the uniqueness constraint lookup (e.g. conditions: -> { where(status: 'active') }).
  • :case_sensitive – Looks for an exact match. Ignored by non-text columns (true by default).
  • :allow_nil – If set to true, skips this validation if the attribute is nil (default is false).
  • :allow_blank – If set to true, skips this validation if the attribute is blank (default is false).
  • :if – Specifies a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.
  • :unless – Specifies a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

 

class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true

  validates_uniqueness_of :name, scope: [:imageable_id, :imageable_type]
end

 

这次做新项目的时候,把图片都放在了一个表里,其他表中不再存图片信息,通过多态关联建立表之间的关系。

(1)新建picture表, component表不需要处理

class CreatePictures < ActiveRecord::Migration[5.0]
  def change
    create_table :pictures do |t| 
      t.integer :imageable_id
      t.string :imageable_type
      t.string :name
      t.string :md5
      t.string :url
      t.timestamps
    end 

    add_index :pictures, [:imageable_type, :imageable_id]
  end 
end

(2)关于model的关联

多态关联的文档 http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

A slightly more advanced twist on associations is the polymorphic association.

With polymorphic associations, a model can belong to more than one other model, on a single association.

For example, you might have a picture model that belongs to either an employee model or a product model.

Here’s how this could be declared:

class Component < ApplicationRecord
  serialize :hints, Hash

  has_many :pictures, as: :imageable
  accepts_nested_attributes_for :pictures, reject_if: proc { |attributes| attributes['md5'].blank? || attributes['url'].blank? }
end
class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true

end

对下拉框的处理

  PICTURE_NAME = {
    '海报图' => 'poster',
    '背景' => 'background',
    '左下角角标' => 'left_bottom_corner',
    '右下角角标' => 'right_bottom_corner',
    '左上角角标' => 'left_top_corner',
    '右上角角标' => 'right_top_corner'
  }

  def picture_name picture_name
    PICTURE_NAME.invert[picture_name]
  end

关于多态关联的Instance Public methods: http://api.rubyonrails.org/

 

accepts_nested_attributes_for(*attr_names)

Defines an attributes writer for the specified association(s).

Supported options:

:allow_destroy
If true, destroys any members from the attributes hash with a _destroy key and a value that evaluates to true(eg. 1, ‘1’, true, or ‘true’). This option is off by default.

:reject_if
Allows you to specify a Proc or a Symbol pointing to a method that checks whether a record should be built for a certain attribute hash.

The hash is passed to the supplied Proc or the method and it should return either true orfalse. When no :reject_if is specified,

a record will be built for all attribute hashes that do not have a _destroyvalue that evaluates to true.

Passing :all_blank instead of a Proc will create a proc that will reject a record where all the attributes are blank excluding any value for _destroy.

:limit
Allows you to specify the maximum number of associated records that can be processed with the nested attributes.

Limit also can be specified as a Proc or a Symbol pointing to a method that should return a number.

If the size of the nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecordsexception is raised.

If omitted, any number of associations can be processed.

Note that the :limit option is only applicable to one-to-many associations.

:update_only
For a one-to-one association, this option allows you to specify how nested attributes are going to be used when an associated record already exists.

In general, an existing record may either be updated with the new set of attribute values or be replaced by a wholly new record containing those values.

By default the :update_onlyoption is false and the nested attributes are used to update the existing record only if they include the record’s:id value.

Otherwise a new record will be instantiated and used to replace the existing one.

However if the:update_only option is true, the nested attributes are used to update the record’s attributes always,

regardless of whether the :id is present. The option is ignored for collection associations.

Examples:

# creates avatar_attributes=
accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
# creates avatar_attributes=
accepts_nested_attributes_for :avatar, reject_if: :all_blank
# creates avatar_attributes= and posts_attributes=
accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
如果在编辑或者新建component的时候,传的picture相关的参数里带有id,那么这条图片记录会被修改,不会被新建。

If the hash contains an id key that matches an already associated record, the matching record will be modified:

member.attributes = {
  name: 'Joe',
  posts_attributes: [
    { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
    { id: 2, title: '[UPDATED] other post' }
  ]
}

member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
member.posts.second.title # => '[UPDATED] other post'


(3)controller里的处理

 Nested Parameters

http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

  private
    def set_component
      @component = Component.find(params[:id])
    end 

    def component_params
      params.require(:component).permit(:release_id, 
                                        :unitary, {pictures_attributes: [:id, :imageable_type, :imageable_id, :name, :url, :md5]},
                                        :remark, component_ids: [], hints: [:left, :mid, :right]
                                        )
    end 

(4)_form里的处理

  <div class="image-group">
    <% @component.pictures.each do |p| %>
      <%= hidden_field_tag  'component[pictures_attributes][][id]', p.id %>
      <div class="form-group">
        <%= f.label 'name', class: 'col-sm-2 control-label' %>
        <div class="col-sm-4">
          <%= text_field_tag 'component[pictures_attributes][][name]', @component.picture_name(p.name), class: 'form-control' %>
        </div>
      </div>

      <div class="form-group">
        <%= f.label 'md5', class: 'col-sm-2 control-label' %>
        <div class="col-sm-4">
          <%= text_field_tag 'component[pictures_attributes][][md5]', p.md5, class: 'form-control' %>
        </div>
      </div>

      <div class="form-group">
        <%= f.label 'url', class: 'col-sm-2 control-label' %>
        <div class="col-sm-4">
            <%= image_tag p.url, :width => 300 %><br/>
        </div>
        <div class="col-sm-4">
          <%= text_field_tag 'component[pictures_attributes][][url]', p.url, class: 'form-control' %>
        </div>
      </div>
    <% end %>
  </div>

 

Rather than using Strings as the keys in a Hash, it’s better practice to use Symbols.

Symbols are just like Strings except they’re faster and take up less memory. The reason Symbols are so efficient is that they are immutable; they cannot be changed, so Ruby doesn’t have to allocate as much memory. Strings on the other hand, can be changed, so Ruby allocates more memory to allow for that. If you want a more thorough explanation of why they are faster, check out this blog post.

 

Let’s try using them as keys in a Hash. Here’s a version of a Hash that uses Strings as keys:

kitten = {
  "name" => "Blue Steele",
  "breed" => "Scottish Fold",
  "age" => "13 weeks"
}

We can rewrite it using Symbols:

kitten = {
  :name => "Blue Steele",
  :breed => "Scottish Fold",
  :age => "13 weeks"
}

Aside from the slight performance boost, another good reason to use Symbols is that Ruby 1.9 introduced a “shortcut” syntax for declaring Hashes with Symbols as keys. We could rewrite the above Hash as:

kitten = {
  name: "Blue Steele",
  breed: "Scottish Fold",
  age: "13 weeks"
}

It saves us having to type those annoying hash rockets (=>), and it closely models the syntax of other languages like JavaScript.

To wrap up, it’s a good idea to use Symbols as keys in a Hash because they’re slightly faster than Strings, and Ruby provides us a nice shortcut syntax.

 

https://github.com/ruby-grape/grape

https://github.com/ruby-grape/grape#param

 

 

requires :subject_id_list, type: Array[String], allow_blank: false

请求的时候只能依次请求

http://111.11.1.1:1100/api/v1/ats?subject_id_list[]=1&subject_id_list[]=2

 

import UIKit

class ViewController: UIViewController {
    
    var time = 0
    
    func result(){
        time++
        print(time)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var timer = NSTimer()
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: ("result"), userInfo: nil, repeats: true)
        
    }

 

Grape,为API设计而生DSL(Domain Specified Language),官网地址: http://intridea.github.io/grape

http://intridea.github.io/grape/docs/index.html

(1)描述性的API构建方式,代码可读性非常强

(2)提供了构建Restful API的一套工具,如参数约束,路径约束,版本管理等

(3)提供了JSON/XML/TXT格式的渲染工具

demo的地址是https://github.com/shiralwz/grape_api

module HelloApi
  require 'grape'

  class OneAPI < Grape::API
    resource :apis do
      format :json

      get 'hello' do
        {message: "hello #{params[:name]} via GET"}
      end 

      post 'hello' do
        {message: "hello #{params[:name]} via POST"}
      end 
    end 

  end 

end
Rails.application.routes.draw do

  mount HelloApi::OneAPI => '/' 
end

rails s

localhost:3000/apis/hello.json?name=mike

如果不需要apis这个命名空间可以直接删除 app/model/hello_api.rb里的第五行 resource :apis do 和第十五行 end