Proactive Units for Practical Applications
How to send sms from ror project?
วันนี้นำวิธีการส่ง sms แบบชาวโปรแกรมเมอร์มาฝากกันคร๊ะ ก้อคือว่าแทนที่เราจะส่ง sms จากมือถือก้อเปลี่ยนเป้นเขียนโค้ดขึ้นมาเองแล้วส่งหา….กันดีกว่ามั๊ยจ๊ะ
ดูเท่ส์ดีว่าป่ะ…อิอิ
เริ่มจาก…(เราใช้ ide netbeans น่ะ..มันง่ายดีน่ะ)
1. สมัคร account http://www.clickatell.com/developers/clickatell_api2.php และเพิ่ม http service ใน account ด้วยจากนั้นก้อจะได้ API key เก็บไว้ดีๆล่ะอันนี้สำคัญน่ะค่ะ
2. install gem=> clickatell
3. สร้างโมลเดล sms.rb เพิ่มโค้ดลงดังนี้
require ‘clickatell’
class SMS
def initialize(config)
@config = config
end
def create(recipient, message_text)
api.send_message(recipient, message_text)
end
private
def api
@api ||= Clickatell::API.authenticate(
@config[:api_key],
@config[:username],
@config[:password]
)
end
end
4. configuration=>environments=>product.rb เพิ่มโค้ดดังนี้
CLICKATELL_CONFIG = YAML.load(File.open(File.join(RAILS_ROOT, ‘config’, ‘clickatell.yml’)))
5. configuration=> clickatell.yml เพิ่มโค้ดดังนี้
api_key: xxxxx
username: mai
password: xxxx
6. configuration=> routes.rb เพิ่มโค้ดดังนี้
ActionController::Routing::Routes.draw do |map|
map.resource :sms
end
7. หน้า view สร้างหน้าเวบที่ต้องการให้ผู้ใช้กรอกข้อมูลเพื่อส่ง sms ถึงผู้รับ
<% form_tag '/sms', :method => :post do -%>
<%= text_field_tag "recipient" %>
<%= text_area_tag "message_text" %>
<%= submit_tag "Send SMS" %>
<% end %>
8. ส่วนของ controller
class SmsController < ApplicationController
def create
sms = SMS.new(CLICKATELL_CONFIG)
sms.create(params[:recipient], params[:message_text])
flash[:notice] = "Message sent succesfully!"
redirect_to :back
rescue Clickatell::API::Error => e
flash[:error] = “Clickatell API error: #{e.message}”
redirect_to :back
end
end
9. เสร็จแล้วจ้าา…
แหล่งที่มา:
http://lukeredpath.co.uk/blog/sending-sms-messages-from-your-rails-application.html
Last 5 posts by on_the_way
- การหาค่า max/min by RoR - January 7th, 2010
- How to sent email by using ror? - January 7th, 2010
- Ruby can connect Multiple database... - January 7th, 2010
- โพสข้อความใน twitter แต่โผล่ใน Facebook - October 30th, 2009
- ใครอยากให้ตังเพิ่มใน Friend for sale แบบไม่ต้องจ่ายตังบ้างยกมือขึ้น.. - October 29th, 2009
