Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

ค้นพบ Hidden Gems: ฟีเจอร์ powerful ที่พลาดใน Rails 4.2

Beta แรกของ Rails 4.2 ประกาศสัปดาห์ที่แล้ว และดู amazing อยู่แล้ว ผม excited ใช้ ActiveJob, Web Console, Adequate Record, Foreign Key support ในแอปตัวเอง

แตความสวยงามของ Rails อยู่ที่รายละเอียด และถ้าขุดนิดหน่อย จะเจอ features ที่โฆษณาน้อย แตปรับปรุง daily work กับ Rails มาก

Easily Load Config Files

โอเค ผมอาจ biased แตมี built-in way โหลด config files จะเก๋บมาก

config_for ใหม่ใน Rails 4.2 ทำงานพอดีกับคาดหวัง:

config/redis.yml
development: host: localhost port: 6379 test: host: localhost port: 6379 production: host: redis-production port: 6379 
irb(main):001:0> Rails.application.config_for(:redis) => {"host"=>"localhost", "port"=>6379} 

คือ เรียก config_for(:redis) มันหา config/redis.yml parse และคืน config สำหรับ RAILS_ENV ปัจจุบัน

มันยังรองรับ ERB ใน yaml:

config/redis.yml
development: host: localhost port: <%= ENV['REDIS_PORT'] %> test: host: localhost port: <%= ENV['REDIS_PORT'] %> production: host: redis-production port: <%= ENV['REDIS_PORT'] %> 
$ REDIS_PORT=6380 bin/rails c Loading development environment (Rails 4.2.0.beta1) irb(main):001:0> Rails.application.config_for(:redis) => {"host"=>"localhost", "port"=>6380} 

ถ้า configure services เยอะในแอป จะทำ initializers อ่านง่ายมาก

Bootstrapping Your Apps

Rails apps ส่วนใหญ่ต้อง run commands ก่อนลองได้ แม้ mostly-empty Rails apps ต้อง setup database ก่อนจะ boot

ดังนั้น Rails convention over configuration อีกครั้ง สร้างที่สำหรับ setup code: bin/setup

Default ดีอยู่แล้ว แต bin/setup ยังเป็นที่วาง code อื่นๆ ที่ต้องการ start app

ตอนนี้เป็น convention ถ้าเขียน bootstrap script สำหรับแอปแล้ว переименуйте เป็น bin/setup ให้คนใช้แอปเริ่มได้ง่าย

bin/setup ลด decision หนึ่งตอน generate Rails apps ใหม่ และพอคุ้นเคยรัน bin/setup หลัง git pull จะไม่ต้องจำรัน rake db:setup ตอน generate app ใหม่

Transform Hash Values

อีกอย่างที่ต้องการบ่อยพออยาก built-in ใน Ruby ตอนเรียก transform_values บน hash มันทำงานเหมือน map บน hash values และคืน hash ใหม่ keys เดิม กับ values ที่เปลี่ยน:

h = {a: 1, b: 2, c: 3} h.transform_values { |v| v * 2 } # => {a: 2, b: 4, c: 6} 

เรียบง่าย แตประหลาดใจว่ามัน handy บ่อยแค่ไหน

Bonus: More Configuration!

Rails 4.2 ให้วิธีง่ายตั้ง global config ของตัวเอง:

Rails.application.config.x.some_configuration_key = "Some Value" Rails.application.config.x.some_configuration_key # => "Some Value" Rails.configuration.x.some_configuration_key # => "Some Value" 

ใช้ดีมากตอนรวมกับ config_for:

app_config = Rails.application.config_for(:app) Rails.application.config.x.block_phone_calls = app_config["block_phone_calls"] 

And There's More!

ดูเหมือน Rails 4.2 จะเป็น release amazing แต refinements เล็กๆ น้อยๆ ที่ทำให้ทำงานใน Rails ทุกวันสนุก ถ้ายังไม่ได้ ลองอ่าน 4.2 Release Notes เร็วๆ ดูว่ามี improvements อื่นๆ ที่ช่วยได้อะไรบ้าง

(และถ้า เจอ cool stuff อย่ากินเอง แชร์ที่นี่ เราเรียนรู้ร่วมกัน!)