王筝的博客
ruby学习

 

$ sudo apt-get install p7zip

$ p7zip -d  aaa.7z

 

How to use the like query with Mongoid . Basically I wanted something like the familiar SQL query:

SELECT * FROM Apps WHERE name LIKE ‘%aaa%’

I couldn’t find anything similar in the Mongoid documentation, but according to the MongoDB documentation you can do regex searches.

Apps.where(name: /aaa/)

Package.where(title: /博影/).first

title = “博影”

Package.where(title: /#{title}/)

注意这行语句在vim里会被误导,vim会把#以后的当作注释,忽略这一点啊.不影响执行效果

现在觉得mongoid很优雅啊,哈哈.

 

http://blog.csdn.net/kunshan_shenbin/article/details/7249713
http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

 

还在为表单嵌套而苦恼么,看看accepts_nested_attributes_for方法吧,今天在项目里用过之后,更爱这门语言了.

# eoncoding: UTF-8

class Package
include Mongoid::Document
include Mongoid::Timestamps
include ImageUploadable
store_in collection: ‘all_apps’

field :language, type: String, default: ‘中文’
field :url, as: :download_url, type: String
field :intro_icons, type: Array, default: []
field :updated_on, type: Date
field :position, type: Integer, default: 0
field :is_deleted, type: Boolean, default: false

index code: 1
index package: 1

has_many :recommend_apps, foreign_key: ‘app_id’
accepts_nested_attributes_for :recommend_apps

—————————————-

class RecommendApp
include Mongoid::Document
include Mongoid::Timestamps
include ImageUploadable

validates :app_id, presence: true

validates :type, inclusion: { in: TYPES.keys }
validates :app_id, uniqueness: { scope: :type }

belongs_to :package, foreign_key: ‘app_id’

————————————

<%= form_for @recommend_app, html: { class: package_form_class(@recommend_app), role: ‘form’ } do |f| %>

<div class=”form-group”>
<%= f.label :position, “推荐位置”, class: “col-sm-2 control-label” %>
<div class=”col-sm-3″>
<%= f.text_field :position,:class =>”form-control” %>
</div>
</div>

<%= fields_for :package do |package| %>

<div class=”form-group”>
<%= package.label :title, “名称”, class: “col-sm-2 control-label” %>
<div class=”col-sm-3″>
<%= package.text_field :title ,:class =>”form-control” %>
</div>
</div>

<% end %>

—————————————

recommend_apps_controller.rb

def edit
@package = @recommend_app.package
end

def update
old_position = @recommend_app.position
if @recommend_app.update_attributes recommend_app_params
@package = @recommend_app.package
if @package.update_attributes package_params
@recommend_app.adjust_recommend_app_position(@recommend_app.position)
redirect_to recommend_apps_path, notice: ‘操作成功’
end
else
render :edit
end
end

—————————————————-

对于fields_for(record_name, record_object = nil, fields_options = {}, &block)

可以看下这个文档

http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for

 

http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

creates seven different routes in your application, all mapping to the Photos controller:

HTTP Verb Path Controller#Action Used for
GET /photos photos#index display a list of all photos
GET /photos/new photos#new return an HTML form for creating a new photo
POST /photos photos#create create a new photo
GET /photos/:id photos#show display a specific photo
GET /photos/:id/edit photos#edit return an HTML form for editing a photo
PATCH/PUT /photos/:id photos#update update a specific photo
DELETE /photos/:id photos#destroy delete a specific photo

 

[31] pry(main)> ‘packages’.classify
=> “Package”

[33] pry(main)> ‘packages’.classify.constantize
=> Package

[40] pry(main)> hash = {key: ‘value’}
=> {:key=>”value”}
[41] pry(main)> hash[:key]
=> “value”
[42] pry(main)> hash[‘key’]
=> nil

[44] pry(main)> hash = {key: ‘value’}.with_indifferent_access
=> {“key”=>”value”}

[45] pry(main)> hash[:key]
=> “value”
[46] pry(main)> hash[‘key’]
=> “value”
[47] pry(main)> hash[‘key’]
=> “value”

[49] pry(main)> app
=> #<RecommendApp _id: 539e995277616e7f74000000, created_at: 2014-06-16 07:14:26 UTC, updated_at: 2014-06-16 07:14:26 UTC, type: 1, position: 0, app_id: BSON::ObjectId(‘53970af477616e1878d40100′)>

[50] pry(main)> app.position
=> 0

[51] pry(main)> app.read_attribute :position
=> 0

[52] pry(main)> app.type
=> 1
[53] pry(main)> app.type_human

 

http://git-scm.com/book/en/Customizing-Git-Git-Configuration

$ git config –global core.editor vim

 

http://www.skorks.com/2009/09/ruby-exceptions-and-exception-handling/

 

Rescuing Exceptions Inside Methods

If we are inside a method and we want to rescue some exceptions, we don’t actually need a begin .. end block since the method definition itself will act in that capacity. So, we can do something like this:

def some_method
  p 'Hello method'
  raise
  p 'Bye method'
rescue
  p 'Rescuing exceptions'
end
some_method

which print out:

"Hello method"
"Rescuing exceptions"
We have rescued an exceptions without having a begin .. end block.
------------------------------------------------------------------
def xxx
   ...
rescue OpenURI::HTTPError, OpenURI::HTTPRedirect
  false
end

 

 

vim route.rb

resources :fetched_apps do
member do
patch :import
end
end

 

spring rake routes

recommend_apps GET /recommend_apps(.:format) recommend_apps#index
POST /recommend_apps(.:format) recommend_apps#create

import_fetched_app PATCH  /fetched_apps/:id/import(.:format)     fetched_apps#import

第三条路由需要传入id参数才能拼完整

now let’s figure out the diference between the p_helper.rb and the f_helper.rb

 def render_recommend_info(package, recommend_type_human)
    recommend_type = RecommendApp::TYPES.invert[recommend_type_human]
    recommend_app = package.recommend_apps.where(type: recommend_type).first

    if recommend_app
      url = recommend_app_path(recommend_app)
      clazz = 'fa fa-check-square-o'
      method = :delete
      title = "取消推荐到'#{recommend_type_human}'"
    else
      url = recommend_apps_path(recommend_app: { type: recommend_type, app_id: package.id.to_s })
      clazz = 'fa fa-square-o'
      method = :post
      title = "推荐到'#{recommend_type_human}'"
    end

link_to url, remote: true, method: method, title: title, data: { toggle: ‘tooltip’ } do
content_tag :i, nil, class: clazz
end
end

————————————————

  def render_import_app(fetched_app)
    if fetched_app.already_imported
      url = fetched_app_path(fetched_app)//传入id,可以在controller里取到
      clazz = 'fa fa-check-square-o'
      method = :get
      title = "已导入"
    else
      url = import_fetched_app_path(fetched_app)
      clazz = 'fa fa-square-o'
      method = :patch
      title = "可导入"
    end

    link_to url, remote: true, method: method, title: title, data: { toggle: 'tooltip' } do
      content_tag :i, nil, class: clazz
    end
  end

now turn to the f_controller.rb

def  import
    params[:id]
    .....
end

 

 

https://github.com/peleteiro/progressbar

gem install progressbar

gem 'progressbar', '~> 0.21.0'
% irb --simple-prompt -r progressbar
>> pbar = ProgressBar.new("test", 100)
=> (ProgressBar: 0/100)
>> 100.times {sleep(0.1); pbar.inc}; pbar.finish
test:          100% |oooooooooooooooooooooooooooooooooooooooo| Time: 00:00:10
=> nil

>> pbar = ProgressBar.new("test", 100)
=> (ProgressBar: 0/100)
>> (1..100).each{|x| sleep(0.1); pbar.set(x)}; pbar.finish
test:           67% |oooooooooooooooooooooooooo              | ETA:  00:00:03

>> ProgressBar.new("test", 100) do |pbar|
>>   100.times { sleep(0.1); pbar.inc }
>> end
test:          100% |oooooooooooooooooooooooooooooooooooooooo| Time: 00:00:10

def download_apk!
require ‘open-uri’
require ‘digest’
require ‘fileutils’

return false if is_dead_download_url?
return false if is_apk_downloaded?

tmp_file = Tempfile.new [package_name, “.apk”]
File.open(tmp_file, ‘wb’) do |file_to_save|
pbar = nil

open(download_url, “rb”, :content_length_proc => lambda {|t|
if t && 0 < t
pbar = ProgressBar.new(“…”, t)
pbar.file_transfer_mode
end
},
:progress_proc => lambda {|s|
pbar.set s if pbar
}) { |file_to_download| file_to_save.write(file_to_download.read) }
end

apk_md5 = Digest::MD5.file(tmp_file).hexdigest
apk_path = File.join Settings.apks_dir, “#{package_name}.#        {apk_md5}.apk”

FileUtils.mkdir_p Settings.apks_dir
FileUtils.mv tmp_file, apk_path

package_info = dump_package_info apk_path
update_attributes package_info.merge(md5: apk_md5)
apk_path
rescue OpenURI::HTTPError, OpenURI::HTTPRedirect
false
end

————————————————————————————-

Tempfile

默认存储路径是 /tmp
A utility class for managing temporary files. When you create a Tempfile object, it will create a temporary file with a unique filename. A Tempfile objects behaves just like a File object, and you can perform all the usual file operations on it: reading data, writing data, changing its permissions, etc. So although this class does not explicitly document all instance methods supported by File, you can in fact call any File instance method on a Tempfile object.
require 'tempfile'

file = Tempfile.new('foo')
file.path      # => A unique filename in the OS's temp directory,
               #    e.g.: "/tmp/foo.24722.0"
               #    This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read      # => "hello world"
file.close
file.unlink    # deletes the temp file
http://ruby-doc.org/core-2.1.2/File.html#method-c-join
join(string, …) 

Returns a new string formed by joining the strings using File::SEPARATOR.

File.join("usr", "mail", "gumby")   #=> "usr/mail/gumby"
real_path = File.join Settings.real_dir, "#{real_name}.#{aaa}.apk"



http://ruby-doc.org/core-2.1.2/Marshal.html#method-c-dump
dump( obj [, anIO] , limit=-1 ) → anIO

Serializes obj and all descendant objects. If anIO is specified, the serialized data will be written to it, otherwise the data will be returned as a String. If limit is specified, the traversal of subobjects will be limited to that depth. If limit is negative, no checking of depth will be performed.

class Klass
  def initialize(str)
    @str = str
  end
  def say_hello
    @str
  end
end

o = Klass.new("hello\n")
data = Marshal.dump(o)
obj = Marshal.load(data)
obj.say_hello  #=> "hello\n"
-----------------------------------------------------