熱門文章

顯示具有 ruby 標籤的文章。 顯示所有文章
顯示具有 ruby 標籤的文章。 顯示所有文章

2017年2月20日 星期一

常見的 Ruby on Rails 工程師面試問題

常見的 Ruby on Rails 工程師面試問題

收錄一些業界常見/常問的面試問題和翻譯解答

解答不見得完整和精確,但在面試的環境下回答應該是足夠的

有需要改正或有什麼要新增 / 補充的地方也請大家發 PR

開始閱讀

2016年11月6日 星期日

[ruby]URI::InvalidURIError (bad URI(is not URI?)

我遇到這個error是在irb裡使用open-uri都正常,但是改寫成rb檔時出現的

/usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/uri/rfc3986_parser.rb:67:in `split': bad URI(is not URI?): http://google.com.au (URI::InvalidURIError)
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/uri/rfc3986_parser.rb:73:in `parse'
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/uri/common.rb:227:in `parse'
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/open-uri.rb:34:in `open'

from a.rb:16:in `<main>'


後來找到該解答如下

I got into trouble with URI.split (returning this error), I don't know if this helps you, but I will post here some warnings for also someone else having this error:
  1. Check your url is not nil, and it's a valid one.
  2. Do URI.encode(url) before URI.parse (to avoid special characters)
  3. Do strip to the string you pass to URI.parse (to avoid leading and trailing whitespaces).
All in one:
uri = URI.parse(URI.encode(url.strip))

解決方法:

puts "請輸入: "
html=gets.strip
在gets後面加上 .strip 去掉空白字元就行了



2016年10月31日 星期一

[Rails]資料庫可以使用哪些資料型態?如何存array,json ?

Here are all the Rails 4 (ActiveRecord migration) datatypes:
  • :binary
  • :boolean
  • :date
  • :datetime
  • :decimal
  • :float
  • :integer
  • :bigint
  • :primary_key
  • :references
  • :string
  • :text
  • :time
  • :timestamp
If you use PostgreSQL, you can also take advantage of these:
  • :hstore
  • :json
  • :array
  • :cidr_address
  • :ip_address
  • :mac_address
They are stored as strings if you run your app with a not-PostgreSQL database.
Edit, 2016-Sep-19:
There's a lot more postgres specific datatypes in Rails 4 and even more in Rails 5.

[rails]do each 用法 (with index)

在ruby裡面,大家都用do each 的方法來完成其他程式的for 迴圈

基本的用法  each do


irb(main):013:0> a=[1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
irb(main):022:0> a.each do |b|
irb(main):023:1* puts b    
irb(main):024:1> end
1
2
3
4
5
6
=> [1, 2, 3, 4, 5, 6]



這樣可以達到for loop的功效 且很簡短 不用再寫 當...大於...時..i++ 這麼長了
但,有一個問題,那當我要有 i++ 這樣遞增或遞減的序號時怎麼做?

答案很簡單  each_with_index do

irb(main):030:0> b=[12,22,23,44,66,22]
=> [12, 22, 23, 44, 66, 22]
irb(main):031:0> b.each_with_index do |b,index|
irb(main):032:1* puts "我是第#{index+1} 筆資料,為'#{b}' 謝謝"
irb(main):033:1> end
我是第1 筆資料,為'12' 謝謝
我是第2 筆資料,為'22' 謝謝
我是第3 筆資料,為'23' 謝謝
我是第4 筆資料,為'44' 謝謝
我是第5 筆資料,為'66' 謝謝
我是第6 筆資料,為'22' 謝謝
=> [12, 22, 23, 44, 66, 22]


參考:http://ruby-doc.org/core-1.8.7/Enumerable.html#method-i-each_with_index


2016年10月17日 星期一

[Rails]AJAX筆記-使用內建方式

使用內建ajax的方法

  1. 在from_for 加入 remote:true
  2. 在controller的相對應action,加入format.js (create action)
  3. 新增相對應action的js擋( create.js.erb)











when there is a file field in a form is submitted via AJAX.
在使用Ajax時,如果form裡面有file_field遇到問題

ActionController::InvalidAuthenticityToken error. 



ActionController::InvalidAuthenticityToken in StoresController#create

Avoiding ActionController::InvalidAuthenticityToken on AJAX calls



Missing Authenticity Token in Remote Forms w/ File Upload Field(s) #22807




解決方法一:在form_for 加入  :authenticity_token => true
可以成功執行Create Action,但是不會以Ajax的方式執行

<%= form_for @some_model, :remote => true, :authenticity_token => true do |f| %>
<% end %>


解決方法二:

當form_for 改為 :remote=>true時 ,form 將不會包含 authenticity_token
因為以下預設值為false
config.action_view.embed_authenticity_token_in_remote_forms = false 


將其改為true即可修正錯誤

config.action_view.embed_authenticity_token_in_remote_forms = true
官方解釋
  • config.action_view.embed_authenticity_token_in_remote_forms allows you to set the default behavior for authenticity_token in forms with remote: true. By default it's set to false, which means that remote forms will not include authenticity_token, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the meta tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass authenticity_token: true as a form option or set this config setting to true.

2016年9月22日 星期四

[文字編輯器]Sublime Text好用套件-Emmet




手動安裝可參考 :https://www.minwt.com/webdesign-dev/html/11624.html




這邊使用的是sublime2


安裝步驟

1.下載Sublime Text https://www.sublimetext.com/3


2.安裝Package Control

2-1開啟sublime 並開啟Console (位置在最上方的view > Show Console


 可以看到下方出現console
2-2 輸入相對版本的指令 https://sublime.wbond.net/installation

Sublime Text 2

import urllib2,os,hashlib; h = '261dd1222b4693ce6d4f85f9c827ac06' + '6d5ab8ebdd020086947172a8a1356bb6'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler()) ); by = urllib2.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); open( os.path.join( ipp, pf), 'wb' ).write(by) if dh == h else None; print('Error validating download (got %s instead of %s), please try manual install' % (dh, h) if dh != h else 'Please restart Sublime Text to finish installation')
2-3 重開


3.安裝Emmet

3-1 開啟package controller  (Sublime Text2 > perferences >Package Control) 
或快捷鍵(command+shift+p)


3-2 選擇 Package Control:Install Package



3-3 Package Control 視窗會消失,請再開啟一次 (command+shift+p),並輸入emmet
選擇第一個( 並非我途中所顯示的那個,因為我已經安裝所以不會顯示)


這個才是正確的Emmet (youtube 截圖 from :https://www.youtube.com/watch?v=8n923UBjV9w)

3-4重開 !!完成




再來是操作 ,在sublime 開啟 html檔案,以下是簡易的教學影片

輸入 .[class name] 後,按鍵盤的Tab鍵 即可變成
<div class="[class name]"></div>
幫你省下許多時間






更多外掛介紹及教學

http://www.slideshare.net/banPrint/sublime-text-51689543

2016年9月19日 星期一

[Ruby on Rails]上傳app到 Heroku

出處:http://railsgirls.tw/heroku


取得 Heroku

按照 Heroku 官方的快速上手指南的步驟 1 至步驟 3,來註冊、安裝工具包並登入。
教練: 講解將 App 部署到 Heroku,跟傳統自己架伺服器比起來,有什麼好處。

準備妳的 app

版本管理系統

需要把程式碼加到版本管理系統。在終端機裡輸入以下命令:
git init
echo "public/uploads" >> .gitignore
echo "tmp" >> .gitignore
echo "logs" >> .gitignore
git add .
git commit -m "initial commit"
教練:講解使用版本管理系統的好時機。順便解釋 .gitignore 檔案是什麼,並解釋為什麼要忽略某些檔案被傳上去。

更新資料庫

首先,需要讓資料庫在 Heroku 跑起來。Heroku 使用不同於 Rails 預設的資料庫。請修改 Gemfile 的內容:
請將
gem 'sqlite3'
改為
group :development do
  gem 'sqlite3'
end
group :production do
  gem 'pg'
end
執行 bundle install --without production 命令來解決軟體相依問題。
教練: 可以講講 RDBMS 以及 pg 與 sqlite 的差別,請講點 Heroku 的 PostgreSQL 軟體相依細節。

安裝 rails_12factor Gem

接下來,需要在 Gemfile 加入 rails_12factor,讓我們的 app 可以出現在 Heroku。
這個 Gem 調整妳的 Rails App 成為適合在 Heroku 工作的模式,舉例來說,記錄檔存放的地方、靜態檔案的設定(圖片、樣式表以及 JavaScript 檔案)會設定成適合 Heroku 系統的設定。
請修改 Gemfile 的內容:
將
group :production do
  gem 'pg'
end
改為
group :production do
  gem 'pg'
  gem 'rails_12factor'
end
修改好之後到終端機執行 bundle 命令,接著將 Gemfile.lock 提交到妳的程式碼倉庫 (repository):
git commit -a -m "Added rails_12factor gem and updated Gemfile.lock"
教練: 可以說說 Heroku 的記錄檔怎麼用,或是其它相關的東西。

部署 App

建立 App

需要在終端裡輸入 heroku create,在 Heroku 上產生一個新的 Heroku app,妳會看到像是下面的訊息:
Creating evening-sky-7498... done, stack is cedar
http://evening-sky-7498.herokuapp.com/ | git@heroku.com:evening-sky-7498.git
Git remote heroku added
上面的 “evening-sky-7498” 就是妳 Heroku App 的名稱。

上傳程式碼

接著需要將程式碼上傳至 Heroku,輸入 git push heroku master。妳會看到像是下面的輸出:
Counting objects: 134, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (115/115), done.
Writing objects: 100% (134/134), 35.29 KiB, done.
Total 134 (delta 26), reused 0 (delta 0)

-----> Heroku receiving push
-----> Ruby/Rails app detected
-----> Installing dependencies using Bundler version 1.1.2
       Running: bundle install --without development:test --path vendor/bundle --binstubs bin/ --deployment
       Fetching gem metadata from https://rubygems.org/.......
...
-----> Launching... done, v4
       http://evening-sky-7498.herokuapp.com deployed to Heroku
看到 “Launching…” 的訊息表示 App 已經上傳完畢了。

資料庫遷移

接著需要遷移資料庫,跟我們在工作坊時,在自己電腦上做的一樣: heroku run rake db:migrate。
當這條命令執行完畢時,妳可以用產生出來的網址來訪問妳的 App,可以打開這個頁面 http://evening-sky-7498.herokuapp.com/ 看看。也可以在終端裡輸入 heroku open 來開啟網頁。


2016年8月15日 星期一

[rails]form-tag

>>index.html.erb

<%= form_tag(groups_path, method: "get") do %>
  <%= label_tag(:q) %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("搜索") %>
<% end %>
<%= @a %>
</div>


groups_path  :處理的路徑
:q 將被存在 controller 裡相對路徑的 method 裡
此範例是 groupscontroller.rb的 index 裡如下

def index
@groups = Group.all
a = params[:q]
end

對網頁應用程式來說,表單是非常重要的用戶輸入介面。Rails在這方面也提供了很多好用的Helper方法。基本上,Rails處理表單分成兩種類型:
一種是對應到Model物件的新增、修改,我們會使用form_for這個Helper。它的好處在於透過傳入Model物件,可以在修改的時候自動幫你將預設值帶入。例如我們已經在Part1使用過的event表單:
<%= form_for @event do |f| %>
    <%= f.text_field :name %>
    <%= f.submit %>
<% end %>
另一種是就是沒有對應Model的表單,我們使用form_tag這個方法。例如:
<%= form_tag "/search" do %>
    <%= text_field_tag :keyword %>
    <%= submit_tag %>
<% end %>
和form_for有些類似,但是其中不需要傳Block變數f,其中的欄位Helper需要多加_tag結尾。不像form_for的欄位名稱一定要是Model的屬性之一,在form_tag之中的欄位名稱則完全不受限。


form_tag 是啥?跟 form_for 有什麼不一樣?

Adler @ 2015-07-18

2016年8月9日 星期二

2016年7月13日 星期三

[Ruby]Getting a “bad interpreter” error when using brew

http://stackoverflow.com/questions/8864668/getting-a-bad-interpreter-error-when-using-brew

原本都使用正常,但是在安裝 homebrew 之後造成錯誤




嘗試重新安裝 ruby

➜  ~ git:(master) ✗ brew install ruby
==> Installing dependencies for ruby: readline, libyaml, openssl
==> Installing ruby dependency: readline
==> Downloading https://homebrew.bintray.com/bottles/readline-6.3.8.el_capitan.bottle.tar.gz
######################################################################## 100.0%
==> Pouring readline-6.3.8.el_capitan.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local.

OS X provides the BSD libedit library, which shadows libreadline.
In order to prevent conflicts when programs look for libreadline we are
defaulting this GNU Readline installation to keg-only.


Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/readline/lib
    CPPFLAGS: -I/usr/local/opt/readline/include

==> Summary
🍺  /usr/local/Cellar/readline/6.3.8: 46 files, 2.0M
==> Installing ruby dependency: libyaml
==> Downloading https://homebrew.bintray.com/bottles/libyaml-0.1.6_1.el_capitan.bottle.tar.g
######################################################################## 100.0%
==> Pouring libyaml-0.1.6_1.el_capitan.bottle.tar.gz
🍺  /usr/local/Cellar/libyaml/0.1.6_1: 8 files, 312.8K
==> Installing ruby dependency: openssl
==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2h_1.el_capitan.bottle.tar.
######################################################################## 100.0%
==> Pouring openssl-1.0.2h_1.el_capitan.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺  /usr/local/Cellar/openssl/1.0.2h_1: 1,691 files, 12M
==> Installing ruby
==> Downloading https://homebrew.bintray.com/bottles/ruby-2.3.1.el_capitan.bottle.tar.gz
######################################################################## 100.0%
==> Pouring ruby-2.3.1.el_capitan.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink bin/rake
Target /usr/local/bin/rake
already exists. You may want to remove it:
  rm '/usr/local/bin/rake'

To force the link and overwrite all conflicting files:
  brew link --overwrite ruby

To list all files that would be deleted:
  brew link --overwrite --dry-run ruby

Possible conflicting files are:
/usr/local/bin/rake
/usr/local/bin/rdoc
/usr/local/bin/ri
==> Caveats
Emacs Lisp files have been installed to:
  /usr/local/share/emacs/site-lisp/ruby
==> Summary
🍺  /usr/local/Cellar/ruby/2.3.1: 1,260 files, 19.0M
➜  ~ git:(master) ✗ 
➜  ~ git:(master) ✗ 
➜  ~ git:(master) ✗ 
➜  ~ git:(master) ✗ 
➜  ~ git:(master) ✗ 
➜  ~ git:(master) ✗ 
➜  ~ git:(master) ✗ rm '/usr/local/bin/rake'
➜  ~ git:(master) ✗  brew link --overwrite ruby
Linking /usr/local/Cellar/ruby/2.3.1... 1225 symlinks created
➜  ~ git:(master) ✗ brew link --overwrite --dry-run ruby
Warning: Already linked: /usr/local/Cellar/ruby/2.3.1
To relink: brew unlink ruby && brew link ruby
➜  ~ git:(master) ✗ brew unlink ruby && brew link ruby
Unlinking /usr/local/Cellar/ruby/2.3.1... 1225 symlinks removed
Linking /usr/local/Cellar/ruby/2.3.1... 1225 symlinks created
➜  ~ git:(master) ✗ ruby



輸入ruby後 卡住.....

重試

Last login: Wed Jul 13 14:02:14 on ttys002
➜  ~ git:(master) ✗ which ruby
/usr/local/bin/ruby
➜  ~ git:(master) ✗ brew install rbenv ruby-build
==> Installing dependencies for rbenv: autoconf, pkg-config, ruby-build
==> Installing rbenv dependency: autoconf
==> Downloading https://homebrew.bintray.com/bottles/autoconf-2.69.el_capitan.bottle.4.tar.g
######################################################################## 100.0%
==> Pouring autoconf-2.69.el_capitan.bottle.4.tar.gz
==> Caveats
Emacs Lisp files have been installed to:
  /usr/local/share/emacs/site-lisp/autoconf
==> Summary
🍺  /usr/local/Cellar/autoconf/2.69: 70 files, 3.0M
==> Installing rbenv dependency: pkg-config
==> Downloading https://homebrew.bintray.com/bottles/pkg-config-0.29.1.el_capitan.bottle.tar
######################################################################## 100.0%
==> Pouring pkg-config-0.29.1.el_capitan.bottle.tar.gz
🍺  /usr/local/Cellar/pkg-config/0.29.1: 10 files, 627.2K
==> Installing rbenv dependency: ruby-build
==> Downloading https://github.com/rbenv/ruby-build/archive/v20160602.tar.gz
==> Downloading from https://codeload.github.com/rbenv/ruby-build/tar.gz/v20160602
######################################################################## 100.0%
==> ./install.sh
🍺  /usr/local/Cellar/ruby-build/20160602: 282 files, 155.5K, built in 7 seconds
==> Installing rbenv
==> Downloading https://homebrew.bintray.com/bottles/rbenv-1.0.0.el_capitan.bottle.tar.gz
######################################################################## 100.0%
==> Pouring rbenv-1.0.0.el_capitan.bottle.tar.gz
==> Caveats
Rbenv stores data under ~/.rbenv by default. If you absolutely need to
store everything under Homebrew's prefix, include this in your profile:
  export RBENV_ROOT=/usr/local/var/rbenv

To enable shims and autocompletion, run this and follow the instructions:
  rbenv init
==> Summary
🍺  /usr/local/Cellar/rbenv/1.0.0: 36 files, 61.9K

➜  ~ git:(master) ✗ 

➜  ~ git:(master) ✗ brew install ruby
Warning: ruby-2.3.1 already installed
➜  ~ git:(master) ✗ ruby -v

ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

可以看到ruby的版本

➜  ~ git:(master) ✗ rails -v
/usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/rubygems/dependency.rb:319:in `to_specs': Could not find 'railties' (>= 0) among 11 total gem(s) (Gem::LoadError)
Checked in 'GEM_PATH=/Users/QJpioneer/.gem/ruby/2.3.0:/usr/local/lib/ruby/gems/2.3.0:/usr/local/Cellar/ruby/2.3.1/lib/ruby/gems/2.3.0', execute `gem env` for more information
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/rubygems/dependency.rb:328:in `to_spec'
from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:65:in `gem'

from /usr/local/bin/rails:22:in `<main>'

Rails 卻發生錯誤,嘗試重新安裝rails




➜  ~ git:(master) ✗ gem install nokogiri                               
Building native extensions.  This could take a while...
ERROR:  Error installing nokogiri:

ERROR: Failed to build gem native extension.



After upgrading OS X from Mountain Lion to Maverick, encountered errors installing nokogiri. Resolved the error by reinstalling the command line tools.
  • brew doctor
  • xcode-select --install
執行以上兩個後,成功

➜  ~ git:(master) ✗ gem install nokogiri                                  
Building native extensions.  This could take a while...
Successfully installed nokogiri-1.6.8

1 gem installed

➜  ~ git:(master) ✗ gem install rails                             
Fetching: loofah-2.0.3.gem (100%)

Successfully installed loofah-2.0.3
...
Successfully installed rails-5.0.0
26 gems installed
➜  ~ git:(master) ✗ rails -v
Rails 5.0.0