Commit eebffe72 authored by Andi Saurer's avatar Andi Saurer

init

parents
.bundle/
log/*.log
pkg/
spec/dummy/db/*.sqlite3
spec/dummy/log/*.log
spec/dummy/tmp/
spec/dummy/.sass-cache
spec/dummy/config/database.yml
tmp/*
--color
1.9.3@short_message
source "http://rubygems.org"
# Declare your gem's dependencies in short_message.gemspec.
# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.
gemspec
# jquery-rails is used by the dummy application
gem "jquery-rails"
# Declare any dependencies that are still in development here instead of in
# your gemspec. These might include edge Rails or gems from your path or
# Git. Remember to move these dependencies to your gemspec before releasing
# your gem to rubygems.org.
# To use debugger
# gem 'debugger'
# A sample Guardfile
# More info at https://github.com/guard/guard#readme
guard 'rspec' do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
# Rails example
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/(.*)(\.erb|\.haml)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
# Capybara features specs
watch(%r{^app/views/(.+)/.*\.(erb|haml)$}) { |m| "spec/features/#{m[1]}_spec.rb" }
# Turnip features and steps
watch(%r{^spec/acceptance/(.+)\.feature$})
watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
end
Copyright 2013 YOURNAME
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# ShortMessage
## Installation
Add it to your Gemfile:
```ruby
gem 'short_message'
```
Run the following command to install it:
```console
bundle install
```
Run the generator:
```console
rails generate short_message:install
```
And rake the migrations:
```console
rake db:migrate
```
#!/usr/bin/env rake
begin
require 'bundler/setup'
rescue LoadError
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
end
begin
require 'rdoc/task'
rescue LoadError
require 'rdoc/rdoc'
require 'rake/rdoctask'
RDoc::Task = Rake::RDocTask
end
RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'ShortMessage'
rdoc.options << '--line-numbers'
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('lib/**/*.rb')
end
Bundler::GemHelper.install_tasks
module ShortMessage
class ApplicationController < ActionController::Base
end
end
module ShortMessage
module ApplicationHelper
end
end
module ShortMessage
class Mailer < ActionMailer::Base
def recharge_notification amount
mail to: ShortMessage.config.reload_notification_email, :from => ShortMessage.config.default_mail_sender, :subject => "SMS credit recharged", :body => "Your SMS Account has automatically been recharged with #{amount} sms."
end
def voucher_notification amount
mail :to => ShortMessage.config.voucher_notification_email, :from => ShortMessage.config.default_mail_sender, :subject => "SMS credit recharged, please create a voucher", :body => "Please add a voucher:\r\nCustomer: #{ShortMessage.config.user_id}\r\nAmount: #{amount} sms\r\n\r\nThank you!"
end
def recharge_failed_notification amount, message
mail :to => ShortMessage.config.reload_notification_email, :from => ShortMessage.config.default_mail_sender, :subject => "SMS credit recharge failed", :body =>"SMS account could not be recharged with #{amount} sms. Error: #{body}"
end
end
end
require "net/http"
require "net/https"
module ShortMessage
class Message < ActiveRecord::Base
attr_accessible :message_key, :recipient, :sender, :status_code, :text
def status_text
I18n.t("short_message.status.code_#{self.status_code}")
end
def deliver
unless self.sender.blank? and self.recipient.blank? and self.text.blank?
http = Net::HTTP.new(ShortMessage.config.gateway_server)
response, data = http.post(ShortMessage.config.send_file_path, build_deliver_params_string)
if response.code == "200"
# returns something like 0:200: OK (<mobilenumber>:<msgid>):<msgid>
result_set = response.body.gsub("(","").gsub(")","").split(":")
self.status_code = result_set[0].to_i
self.message_key = result_set[3] unless result_set[3].blank?
if self.status_code == 3 and ShortMessage.config.default_reload_amount > 0
if self.recharge
self.deliver
else
self.status_code = 99
return false
end
end
self.save
true
else
false
end
end
end
def recharge amount = ShortMessage.config.default_reload_amount
http = Net::HTTP.new(ShortMessage.config.gateway_server)
response, body = http.post(ShortMessage.config.account_functions_path, build_recharge_params_string(amount))
if response.code == "200"
# returns something like 0:Successful
result_set = response.body.split(":")
if result_set[0] == "0"
logger.info "SMS account successfully charged with #{amount} sms."
Mailer.recharge_notification(amount).deliver unless ShortMessage.config.reload_notification_email.blank?
Mailer.voucher_notification(amount).deliver unless ShortMessage.config.voucher_notification_email.blank?
true
else
logger.warn "SMS account could not be recharged with #{amount} sms. Error: #{body}"
Mailer.recharge_failed_notification(amount, body).deliver unless ShortMessage.config.reload_notification_email.blank?
false
end
else
"#{response.code} #{response.message}"
end
end
private
def build_deliver_params_string
params = []
params << "UserID=#{ShortMessage.config.user_id}"
params << "CCUID=#{ShortMessage.config.ccu_id}"
params << "ID=#{ShortMessage.config.id_string}"
params << "sender=#{CGI.escape(self.sender)}"
params << "receipient=#{CGI.escape(self.recipient)}"
params << "message=#{CGI.escape(self.text.encode('ISO-8859-1', 'utf-8'))}"
params.join("&")
end
def build_recharge_params_string amount
params = []
params << "UserIDFS=#{ShortMessage.config.user_id}"
params << "CCUID=#{ShortMessage.config.ccu_id}"
params << "pay=1"
params << "amount=#{amount}"
params << "idstring=#{ShortMessage.config.id_string}"
params.join("&")
end
end
end
de:
short_message:
status:
code_1: "zugestellt"
code_2: "Fehler"
code_3: "kein Guthaben"
code_4: "zwischengespeichert"
code_8: "anerkannt"
code_9: "gesendet"
code_16: "abgewiesen"
code_99: "Aufladen fehlgeschlagen"
code_100: "erstellt"
en:
short_message:
status:
code_1: "delivered"
code_2: "error"
code_3: "recharge needed"
code_4: "cached"
code_8: "accepted"
code_9: "sent"
code_16: "rejected"
code_99: "recharging failed"
code_100: "created"
ShortMessage::Engine.routes.draw do
end
class CreateShortMessageMessages < ActiveRecord::Migration
def change
create_table :short_message_messages do |t|
t.string :message_key
t.string :sender
t.string :recipient
t.integer :status_code
t.text :text
t.timestamps
end
end
end
module ShortMessage
module Generators
class InstallGenerator < Rails::Generators::Base
desc "Copy ShortMessage configuration files"
source_root File.expand_path('../templates', __FILE__)
def copy_config
template "config/initializers/short_message.rb"
end
end
end
end
ShortMessage.configure do |config|
config.gateway_server = "www1.q-x.ch"
config.gateway_port = "443"
config.send_file_path = "/app/sms/gw1/cust/send.php"
config.account_functions_path = "/app/sms/gw1/cust/accfunc.php"
# enter your details received from provider here
config.user_id = ""
config.ccu_id = ""
config.id_string = ""
config.default_reload_amount = 1000
config.default_mail_sender = "webmaster@your-domain.com"
config.reload_notification_email = "webmaster@your-domain.com"
config.voucher_notification_email = "give-me-money@your-domain.com"
end
\ No newline at end of file
require "short_message/engine"
require "short_message/config"
module ShortMessage
end
require 'active_support/configurable'
module ShortMessage
def self.configure(&block)
yield @config ||= ShortMessage::Configuration.new
end
def self.config
@config
end
class Configuration #:nodoc:
include ActiveSupport::Configurable
config_accessor :gateway_server
config_accessor :gateway_port
config_accessor :send_file_path
config_accessor :account_functions_path
config_accessor :user_id
config_accessor :ccu_id
config_accessor :id_string
config_accessor :default_reload_amount
config_accessor :reload_notification_email
config_accessor :voucher_notification_email
config_accessor :default_mail_sender
def param_name
config.param_name.respond_to?(:call) ? config.param_name.call : config.param_name
end
# define param_name writer (copied from AS::Configurable)
writer, line = 'def param_name=(value); config.param_name = value; end', __LINE__
singleton_class.class_eval writer, __FILE__, line
class_eval writer, __FILE__, line
end
end
\ No newline at end of file
module ShortMessage
class Engine < ::Rails::Engine
isolate_namespace ShortMessage
initializer "short_message.migrate_database" do |app|
Rails.application.config.paths['db/migrate'] += paths['db/migrate'].existent
end
config.generators do |g|
g.test_framework :rspec, :fixture => false
g.fixture_replacement :factory_girl, :dir => 'spec/factories'
g.assets false
g.helper false
end
end
end
module ShortMessage
VERSION = "0.0.1"
end
# desc "Explaining what the task does"
# task :short_message do
# # Task goes here
# end
#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
ENGINE_ROOT = File.expand_path('../..', __FILE__)
ENGINE_PATH = File.expand_path('../../lib/short_message/engine', __FILE__)
require 'rails/all'
require 'rails/engine/commands'
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "short_message/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "short_message"
s.version = ShortMessage::VERSION
s.authors = ["Andi Saurer"]
s.email = ["andi@saurer.me"]
s.homepage = "https://github.com/qinglong15/short_message"
s.summary = "Send short messages to a specific SMS Gateway"
s.description = "Send short messages to a specific SMS Gateway"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "rails", "~> 3.2.12"
# s.add_dependency "jquery-rails"
s.add_development_dependency "mysql2"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "capybara"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "rb-fsevent"
s.add_development_dependency "growl"
end
# encoding: utf-8
module ConfigHelper
def load_default_config
ShortMessage.configure do |config|
config.user_id = "1234"
config.ccu_id = "1234"
config.id_string = "123456789abcdefghijklmnopq"
config.default_reload_amount = 1000
config.reload_notification_email = "webmaster@your-domain.com"
config.voucher_notification_email = "give-me-money@your-domain.com"
config.default_mail_sender = "webmaster@your-domain.com"
end
end
end
== Welcome to Rails
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
This pattern splits the view (also called the presentation) into "dumb"
templates that are primarily responsible for inserting pre-built data in between
HTML tags. The model contains the "smart" domain objects (such as Account,
Product, Person, Post) that holds all the business logic and knows how to
persist themselves to a database. The controller handles the incoming requests
(such as Save New Account, Update Product, Show Post) by manipulating the model
and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, create a new Rails application:
<tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
2. Change directory to <tt>myapp</tt> and start the web server:
<tt>cd myapp; rails server</tt> (run with --help for options)
3. Go to http://localhost:3000/ and you'll see:
"Welcome aboard: You're riding Ruby on Rails!"
4. Follow the guidelines to start developing your application. You can find
the following resources handy:
* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
== Debugging Rails
Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
First area to check is the application log files. Have "tail -f" commands
running on the server.log and development.log. Rails will automatically display
debugging and runtime information to these files. Debugging info will also be
shown in the browser on requests from 127.0.0.1.
You can also log your own messages directly into the log file from your code
using the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@weblog = Weblog.find(params[:id])
@weblog.destroy
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
end
end
The result will be a message in your log file along the lines of:
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
More information on how to use the logger is at http://www.ruby-doc.org/core/
Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
several books available online as well:
* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
These two books will bring you up to speed on the Ruby language and also on
programming in general.
== Debugger
Debugger support is available through the debugger command when you start your
Mongrel or WEBrick server with --debugger. This means that you can break out of
execution at any point in the code, investigate and change the model, and then,
resume execution! You need to install ruby-debug to run the server in debugging
mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
@posts = Post.all
debugger
end
end
So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
=> "[#<Post:0x14a6be8
@attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
#<Post:0x14a6620
@attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
...and even better, you can examine how your runtime objects actually work:
>> f = @posts.first
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you can enter "cont".
== Console
The console is a Ruby shell, which allows you to interact with your
application's domain model. Here you'll have all parts of the application
configured, just like it is when the application is running. You can inspect
domain models, change values, and save to the database. Starting the script
without arguments will launch it in the development environment.
To start the console, run <tt>rails console</tt> from the application
directory.
Options:
* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
made to the database.
* Passing an environment name as an argument will load the corresponding
environment. Example: <tt>rails console production</tt>.
To reload your controllers and models after launching the console run
<tt>reload!</tt>
More information about irb can be found at:
link:http://www.rubycentral.org/pickaxe/irb.html
== dbconsole
You can go to the command line of your database directly through <tt>rails
dbconsole</tt>. You would be connected to the database with the credentials
defined in database.yml. Starting the script without arguments will connect you
to the development database. Passing an argument will connect you to a different
database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
PostgreSQL and SQLite 3.
== Description of Contents
The default directory structure of a generated Ruby on Rails application:
|-- app
| |-- assets
| |-- images
| |-- javascripts
| `-- stylesheets
| |-- controllers
| |-- helpers
| |-- mailers
| |-- models
| `-- views
| `-- layouts
|-- config
| |-- environments
| |-- initializers
| `-- locales
|-- db
|-- doc
|-- lib
| `-- tasks
|-- log
|-- public
|-- script
|-- test
| |-- fixtures
| |-- functional
| |-- integration
| |-- performance
| `-- unit
|-- tmp
| |-- cache
| |-- pids
| |-- sessions
| `-- sockets
`-- vendor
|-- assets
`-- stylesheets
`-- plugins
app
Holds all the code that's specific to this particular application.
app/assets
Contains subdirectories for images, stylesheets, and JavaScript files.
app/controllers
Holds controllers that should be named like weblogs_controller.rb for
automated URL mapping. All controllers should descend from
ApplicationController which itself descends from ActionController::Base.
app/models
Holds models that should be named like post.rb. Models descend from
ActiveRecord::Base by default.
app/views
Holds the template files for the view that should be named like
weblogs/index.html.erb for the WeblogsController#index action. All views use
eRuby syntax by default.
app/views/layouts
Holds the template files for layouts to be used with views. This models the
common header/footer method of wrapping views. In your views, define a layout
using the <tt>layout :default</tt> and create a file named default.html.erb.
Inside default.html.erb, call <% yield %> to render the view using this
layout.
app/helpers
Holds view helpers that should be named like weblogs_helper.rb. These are
generated for you automatically when using generators for controllers.
Helpers can be used to wrap functionality for your views into methods.
config
Configuration files for the Rails environment, the routing map, the database,
and other dependencies.
db
Contains the database schema in schema.rb. db/migrate contains all the
sequence of Migrations for your schema.
doc
This directory is where your application documentation will be stored when
generated using <tt>rake doc:app</tt>
lib
Application specific libraries. Basically, any kind of custom code that
doesn't belong under controllers, models, or helpers. This directory is in
the load path.
public
The directory available for the web server. Also contains the dispatchers and the
default HTML files. This should be set as the DOCUMENT_ROOT of your web
server.
script
Helper scripts for automation and generation.
test
Unit and functional tests along with fixtures. When using the rails generate
command, template test files will be generated for you and placed in this
directory.
vendor
External libraries that the application depends on. Also includes the plugins
subdirectory. If the app has frozen rails, those gems also go here, under
vendor/rails/. This directory is in the load path.
#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
Dummy::Application.load_tasks