repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
beno/devise_sociable
|
vendor/bundle/gems/shoulda-matchers-1.4.2/lib/shoulda/matchers/integrations/test_unit.rb
|
<reponame>beno/devise_sociable
# :enddoc:
require 'test/unit/testcase'
require 'shoulda/matchers/independent'
module Test
module Unit
class TestCase
include Shoulda::Matchers::Independent
extend Shoulda::Matchers::Independent
end
end
end
if defined?(ActionController)
require 'shoulda/matchers/action_controller'
class ActionController::TestCase
include Shoulda::Matchers::ActionController
extend Shoulda::Matchers::ActionController
def subject
@controller
end
end
end
if defined?(ActionMailer)
require 'shoulda/matchers/action_mailer'
module Test
module Unit
class TestCase
include Shoulda::Matchers::ActionMailer
extend Shoulda::Matchers::ActionMailer
end
end
end
end
if defined?(ActiveRecord)
require 'shoulda/matchers/active_record'
require 'shoulda/matchers/active_model'
module Test
module Unit
class TestCase
include Shoulda::Matchers::ActiveRecord
extend Shoulda::Matchers::ActiveRecord
include Shoulda::Matchers::ActiveModel
extend Shoulda::Matchers::ActiveModel
end
end
end
elsif defined?(ActiveModel)
require 'shoulda/matchers/active_model'
module Test
module Unit
class TestCase
include Shoulda::Matchers::ActiveModel
extend Shoulda::Matchers::ActiveModel
end
end
end
end
|
beno/devise_sociable
|
lib/devise_sociable/model.rb
|
require 'devise_sociable/hooks/sociable'
module Devise
module Models
module Sociable
def self.included(base)
base.extend(ClassMethods)
end
#last_access is a time or duration (number)
def active?(last_access)
last_access = last_access.ago if last_access.is_a? Fixnum
self.class.cached?(self) || self.class.actives(last_access).include?(self)
end
def deactivate!
self.class.remove_from_cache(self)
end
module ClassMethods
@@actives_cache = {}
def actives(last_access)
last_access = last_access.ago if last_access.is_a? Fixnum
uses_cookies? ? actives_cookies(last_access) : actives_server(last_access)
end
def cached?(user)
@@actives_cache[user.id].present?
end
def cache_actives(last_access)
actives = {}
self.actives(last_access).each do |user|
actives[user.id] = user
end
@@actives_cache = actives
end
def remove_from_cache(user)
@@actives_cache.delete(user.id)
end
def uses_cookies?
session_store == ActionDispatch::Session::CookieStore
end
def actives_cache
@@actives_cache
end
private
def session_store
Rails.application.config.session_store
end
def actives_server(last_access)
session_class = session_store.session_class
ids = session_class.where("updated_at >= ?", last_access).map do |session|
data = session.data['warden.user.user.session']
key = session.data['warden.user.user.key']
last = data && data['last_request_at']
key && (last >= last_access) ? key[1][0] : nil
end.compact
where(id: ids)
end
def actives_cookies(last_access)
User.where("last_request_at >= ? AND (last_sign_out_at IS NULL OR last_sign_out_at < last_request_at)", last_access)
end
end
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/lib/breakpoint_client.rb
|
require 'breakpoint'
require 'optparse'
require 'timeout'
Options = {
:ClientURI => nil,
:ServerURI => "druby://localhost:42531",
:RetryDelay => 3,
:Permanent => true,
:Verbose => false
}
ARGV.options do |opts|
script_name = File.basename($0)
opts.banner = [
"Usage: ruby #{script_name} [Options] [server uri]",
"",
"This tool lets you connect to a breakpoint service ",
"which was started via Breakpoint.activate_drb.",
"",
"The server uri defaults to druby://localhost:42531"
].join("\n")
opts.separator ""
opts.on("-c", "--client-uri=uri",
"Run the client on the specified uri.",
"This can be used to specify the port",
"that the client uses to allow for back",
"connections from the server.",
"Default: Find a good URI automatically.",
"Example: -c druby://localhost:12345"
) { |Options[:ClientURI]| }
opts.on("-s", "--server-uri=uri",
"Connect to the server specified at the",
"specified uri.",
"Default: druby://localhost:42531"
) { |Options[:ServerURI]| }
opts.on("-R", "--retry-delay=delay", Integer,
"Automatically try to reconnect to the",
"server after delay seconds when the",
"connection failed or timed out.",
"A value of 0 disables automatical",
"reconnecting completely.",
"Default: 10"
) { |Options[:RetryDelay]| }
opts.on("-P", "--[no-]permanent",
"Run the breakpoint client in permanent mode.",
"This means that the client will keep continue",
"running even after the server has closed the",
"connection. Useful for example in Rails."
) { |Options[:Permanent]| }
opts.on("-V", "--[no-]verbose",
"Run the breakpoint client in verbose mode.",
"Will produce more messages, for example between",
"individual breakpoints. This might help in seeing",
"that the breakpoint client is still alive, but adds",
"quite a bit of clutter."
) { |Options[:Verbose]| }
opts.separator ""
opts.on("-h", "--help",
"Show this help message."
) { puts opts; exit }
opts.on("-v", "--version",
"Display the version information."
) do
id = %q$Id: breakpoint_client.rb 40 2005-01-22 20:05:00Z flgr $
puts id.sub("Id: ", "")
puts "(Breakpoint::Version = #{Breakpoint::Version})"
exit
end
opts.parse!
end
Options[:ServerURI] = ARGV[0] if ARGV[0]
module Handlers
extend self
def breakpoint_handler(workspace, message)
puts message
IRB.start(nil, nil, workspace)
puts ""
if Options[:Verbose] then
puts "Resumed execution. Waiting for next breakpoint...", ""
end
end
def eval_handler(code)
result = eval(code, TOPLEVEL_BINDING)
if result then
DRbObject.new(result)
else
result
end
end
def collision_handler()
msg = [
" *** Breakpoint service collision ***",
" Another Breakpoint service tried to use the",
" port already occupied by this one. It will",
" keep waiting until this Breakpoint service",
" is shut down.",
" ",
" If you are using the Breakpoint library for",
" debugging a Rails or other CGI application",
" this likely means that this Breakpoint",
" session belongs to an earlier, outdated",
" request and should be shut down via 'exit'."
].join("\n")
if RUBY_PLATFORM["win"] then
# This sucks. Sorry, I'm not doing this because
# I like funky message boxes -- I need to do this
# because on Windows I have no way of displaying
# my notification via puts() when gets() is still
# being performed on STDIN. I have not found a
# better solution.
begin
require 'tk'
root = TkRoot.new { withdraw }
Tk.messageBox('message' => msg, 'type' => 'ok')
root.destroy
rescue Exception
puts "", msg, ""
end
else
puts "", msg, ""
end
end
end
# Used for checking whether we are currently in the reconnecting loop.
reconnecting = false
loop do
DRb.start_service(Options[:ClientURI])
begin
service = DRbObject.new(nil, Options[:ServerURI])
begin
service.eval_handler = Handlers.method(:eval_handler)
service.collision_handler = Handlers.method(:collision_handler)
service.handler = Handlers.method(:breakpoint_handler)
reconnecting = false
if Options[:Verbose] then
puts "Connection established. Waiting for breakpoint...", ""
end
loop do
begin
service.ping
rescue DRb::DRbConnError => error
puts "Server exited. Closing connection...", ""
exit! unless Options[:Permanent]
break
end
sleep(0.5)
end
ensure
service.eval_handler = nil
service.collision_handler = nil
service.handler = nil
end
rescue Exception => error
if Options[:RetryDelay] > 0 then
if not reconnecting then
reconnecting = true
puts "No connection to breakpoint service at #{Options[:ServerURI]} " +
"(#{error.class})"
puts error.backtrace if $DEBUG
puts "Tries to connect will be made every #{Options[:RetryDelay]} seconds..."
end
sleep Options[:RetryDelay]
retry
else
raise
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/base.rb
|
<gh_stars>1-10
module ActionMailer #:nodoc:
# Usage:
#
# class ApplicationMailer < ActionMailer::Base
# def post_notification(recipients, post)
# @recipients = recipients
# @from = post.author.email_address_with_name
# @headers["bcc"] = SYSTEM_ADMINISTRATOR_EMAIL
# @headers["reply-to"] = "<EMAIL>"
# @subject = "[#{post.account.name} #{post.title}]"
# @body["post"] = post
# end
#
# def comment_notification(recipient, comment)
# @recipients = recipient.email_address_with_name
# @subject = "[#{comment.post.project.client.firm.account.name}]" +
# " Re: #{comment.post.title}"
# @body["comment"] = comment
# @from = comment.author.email_address_with_name
# @sent_on = comment.posted_on
# end
# end
#
# # After this post_notification will look for "templates/application_mailer/post_notification.rhtml"
# ApplicationMailer.template_root = "templates"
#
# ApplicationMailer.create_comment_notification(david, hello_world) # => a tmail object
# ApplicationMailer.deliver_comment_notification(david, hello_world) # sends the email
#
# = Configuration options
#
# These options are specified on the class level, like <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
#
# * <tt>template_root</tt> - template root determines the base from which template references will be made.
#
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
#
# * <tt>server_settings</tt> - Allows detailed configuration of the server:
# * <tt>:address</tt> Allows you to use a remote mail server. Just change it away from it's default "localhost" setting.
# * <tt>:port</tt> On the off change that your mail server doesn't run on port 25, you can change it.
# * <tt>:domain</tt> If you need to specify a HELO domain, you can do it here.
# * <tt>:user_name</tt> If your mail server requires authentication, set the username and password in these two settings.
# * <tt>:password</tt> If your mail server requires authentication, set the username and password in these two settings.
# * <tt>:authentication</tt> If your mail server requires authentication, you need to specify the authentication type here.
# This is a symbol and one of :plain, :login, :cram_md5
#
# * <tt>raise_delivery_errors</tt> - whether or not errors should be raised if the email fails to be delivered.
#
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.
# Sendmail is assumed to be present at "/usr/sbin/sendmail".
#
# * <tt>perform_deliveries</tt> - Determines whether deliver_* methods are actually carried out. By default they are,
# but this can be turned off to help functional testing.
#
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful
# for unit and functional testing.
class Base
private_class_method :new #:nodoc:
cattr_accessor :template_root
cattr_accessor :logger
@@server_settings = {
:address => "localhost",
:port => 25,
:domain => 'localhost.localdomain',
:user_name => nil,
:password => <PASSWORD>,
:authentication => nil
}
cattr_accessor :server_settings
@@raise_delivery_errors = true
cattr_accessor :raise_delivery_errors
@@delivery_method = :smtp
cattr_accessor :delivery_method
@@perform_deliveries = true
cattr_accessor :perform_deliveries
@@deliveries = []
cattr_accessor :deliveries
attr_accessor :recipients, :subject, :body, :from, :sent_on, :headers, :bcc, :cc
def initialize
@bcc = @cc = @from = @recipients = @sent_on = @subject = @body = nil
@headers = {}
end
class << self
def method_missing(method_symbol, *parameters)#:nodoc:
case method_symbol.id2name
when /^create_([_a-z]*)/
create_from_action($1, *parameters)
when /^deliver_([_a-z]*)/
begin
deliver(send("create_" + $1, *parameters))
rescue Object => e
raise e if raise_delivery_errors
end
end
end
def mail(to, subject, body, from, timestamp = nil, headers = nil) #:nodoc:
deliver(create(to, subject, body, from, timestamp, headers))
end
def create(to, subject, body, from, timestamp = nil, headers = nil) #:nodoc:
m = TMail::Mail.new
m.to, m.subject, m.body, m.from = to, subject, body, from
m.date = timestamp.respond_to?("to_time") ? timestamp.to_time : (timestamp || Time.now)
headers.each do |k, v|
m[k] = v
end
return m
end
def deliver(mail) #:nodoc:
logger.info "Sent mail:\n #{mail.encoded}" unless logger.nil?
send("perform_delivery_#{delivery_method}", mail) if perform_deliveries
end
private
def perform_delivery_smtp(mail)
Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain],
server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp|
smtp.sendmail(mail.encoded, mail.from, mail.destinations)
end
end
def perform_delivery_sendmail(mail)
IO.popen("/usr/sbin/sendmail -i -t","w+") do |sm|
sm.print(mail.encoded)
sm.flush
end
end
def perform_delivery_test(mail)
deliveries << mail
end
def create_from_action(method_name, *parameters)
mailer = new
mailer.body = {}
mailer.send(method_name, *parameters)
unless String === mailer.body then
mailer.body = render_body mailer, method_name
end
mail = create(mailer.recipients, mailer.subject, mailer.body,
mailer.from, mailer.sent_on, mailer.headers)
mail.bcc = mailer.bcc unless mailer.bcc.nil?
mail.cc = mailer.cc unless mailer.cc.nil?
return mail
end
def render_body(mailer, method_name)
ActionView::Base.new(template_path, mailer.body).render_file(method_name)
end
def template_path
template_root + "/" + Inflector.underscore(self.to_s)
end
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/lib/dispatcher.rb
|
<gh_stars>1-10
#--
# Copyright (c) 2004 <NAME>
#
# 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.
#++
require 'breakpoint'
class Dispatcher
class <<self
def dispatch(cgi = CGI.new, session_options = ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS)
begin
Breakpoint.activate_drb("druby://localhost:#{BREAKPOINT_SERVER_PORT}", nil, !defined?(FastCGI)) if defined?(BREAKPOINT_SERVER_PORT)
request = ActionController::CgiRequest.new(cgi, session_options)
response = ActionController::CgiResponse.new(cgi)
controller_name, module_name = controller_name(request.parameters), module_name(request.parameters)
require_or_load("application")
require_or_load(controller_path(controller_name, module_name))
controller_class(controller_name).process(request, response).out
rescue Object => exception
ActionController::Base.process_with_exception(request, response, exception).out
ensure
reset_application if Dependencies.load?
Breakpoint.deactivate_drb if defined?(BREAKPOINT_SERVER_PORT)
end
end
private
def reset_application
Dependencies.clear
Dependencies.remove_subclasses_for(ActiveRecord::Base, ActiveRecord::Observer, ActionController::Base)
end
def controller_path(controller_name, module_name = nil)
if module_name
"#{module_name}/#{controller_name.underscore}_controller"
else
"#{controller_name.underscore}_controller"
end
end
def controller_class(controller_name)
Object.const_get(controller_class_name(controller_name))
end
def controller_class_name(controller_name)
"#{controller_name.camelize}Controller"
end
def controller_name(parameters)
parameters["controller"].downcase.gsub(/[^_a-zA-Z0-9]/, "").untaint
end
def module_name(parameters)
parameters["module"].downcase.gsub(/[^_a-zA-Z0-9]/, "").untaint if parameters["module"]
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/environments/test.rb
|
Dependencies.mechanism = :require
ActionController::Base.consider_all_requests_local = true
ActionController::Base.perform_caching = false
ActionMailer::Base.delivery_method = :test
|
beno/devise_sociable
|
vendor/bundle/gems/mocha-0.10.5/lib/mocha/integration/mini_test.rb
|
require 'mocha/api'
require 'mocha/options'
if !MiniTest::Unit::TestCase.ancestors.include?(Mocha::API)
require 'mocha/integration/mini_test/exception_translation'
require 'mocha/integration/mini_test/version_13'
require 'mocha/integration/mini_test/version_140'
require 'mocha/integration/mini_test/version_141'
require 'mocha/integration/mini_test/version_142_to_172'
require 'mocha/integration/mini_test/version_200'
require 'mocha/integration/mini_test/version_201_to_222'
require 'mocha/integration/mini_test/version_230_to_262'
module MiniTest
class Unit
class TestCase
include Mocha::API
alias_method :run_before_mocha, :run
remove_method :run
mini_test_version = begin
Gem::Version.new(MiniTest::Unit::VERSION)
rescue LoadError
Gem::Version.new('0.0.0')
end
$stderr.puts "Detected MiniTest version: #{mini_test_version}" if $mocha_options['debug']
if Gem::Requirement.new('>= 1.3.0', '<= 1.3.1').satisfied_by?(mini_test_version)
include Mocha::Integration::MiniTest::Version13
elsif Gem::Requirement.new('1.4.0').satisfied_by?(mini_test_version)
include Mocha::Integration::MiniTest::Version140
elsif Gem::Requirement.new('1.4.1').satisfied_by?(mini_test_version)
include Mocha::Integration::MiniTest::Version141
elsif Gem::Requirement.new('>= 1.4.2', '<= 1.7.2').satisfied_by?(mini_test_version)
include Mocha::Integration::MiniTest::Version142To172
elsif Gem::Requirement.new('2.0.0').satisfied_by?(mini_test_version)
include Mocha::Integration::MiniTest::Version200
elsif Gem::Requirement.new('>= 2.0.1', '<= 2.2.2').satisfied_by?(mini_test_version)
include Mocha::Integration::MiniTest::Version201To222
elsif Gem::Requirement.new('>= 2.3.0').satisfied_by?(mini_test_version)
$stderr.puts "*** MiniTest integration has not been verified but patching anyway ***" if (Gem::Requirement.new('> 2.6.2').satisfied_by?(mini_test_version)) && $mocha_options['debug']
include Mocha::Integration::MiniTest::Version230To262
else
$stderr.puts "*** No Mocha integration for MiniTest version ***" if $mocha_options['debug']
end
end
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/mocha-0.10.5/test/unit/mockery_test.rb
|
require File.expand_path('../../test_helper', __FILE__)
require 'mocha/mockery'
require 'mocha/state_machine'
class MockeryTest < Test::Unit::TestCase
include Mocha
def test_should_build_instance_of_mockery
mockery = Mockery.instance
assert_not_nil mockery
assert_kind_of Mockery, mockery
end
def test_should_cache_instance_of_mockery
mockery_1 = Mockery.instance
mockery_2 = Mockery.instance
assert_same mockery_1, mockery_2
end
def test_should_expire_mockery_instance_cache
mockery_1 = Mockery.instance
Mockery.reset_instance
mockery_2 = Mockery.instance
assert_not_same mockery_1, mockery_2
end
def test_should_raise_expectation_error_because_not_all_expectations_are_satisfied
mockery = Mockery.new
mock_1 = mockery.named_mock('mock-1') { expects(:method_1) }
mock_2 = mockery.named_mock('mock-2') { expects(:method_2) }
1.times { mock_1.method_1 }
0.times { mock_2.method_2 }
assert_raises(ExpectationError) { mockery.verify }
end
def test_should_reset_list_of_mocks_on_teardown
mockery = Mockery.new
mockery.unnamed_mock { expects(:my_method) }
mockery.teardown
assert_nothing_raised(ExpectationError) { mockery.verify }
end
def test_should_build_instance_of_stubba_on_instantiation
mockery = Mockery.new
assert_not_nil mockery.stubba
assert_kind_of Central, mockery.stubba
end
def test_should_build_new_instance_of_stubba_on_teardown
mockery = Mockery.new
stubba_1 = mockery.stubba
mockery.teardown
stubba_2 = mockery.stubba
assert_not_same stubba_1, stubba_2
end
def test_should_build_and_store_new_state_machine
mockery = Mockery.new
mockery.new_state_machine('state-machine-name')
assert_equal 1, mockery.state_machines.length
assert_kind_of StateMachine, mockery.state_machines[0]
end
def test_should_reset_list_of_state_machines_on_teardown
mockery = Mockery.new
mockery.new_state_machine('state-machine-name')
mockery.teardown
assert_equal 0, mockery.state_machines.length
end
class FakeMethod
def stub; end
def unstub; end
def matches?(other); true; end
end
def test_should_unstub_all_methods_on_teardown
mockery = Mockery.new
stubba = mockery.stubba
stubba.stub(FakeMethod.new)
mockery.teardown
assert stubba.stubba_methods.empty?
end
def test_should_display_object_id_for_mocha_inspect_if_mock_has_no_name
mockery = Mockery.new
mock = mockery.unnamed_mock
assert_match Regexp.new("^#<Mock:0x[0-9A-Fa-f]{1,12}>$"), mock.mocha_inspect
end
def test_should_display_object_id_for_inspect_if_mock_has_no_name
mockery = Mockery.new
mock = mockery.unnamed_mock
assert_match Regexp.new("^#<Mock:0x[0-9A-Fa-f]{1,12}>$"), mock.inspect
end
def test_should_display_name_for_mocha_inspect_if_mock_has_string_name
mockery = Mockery.new
mock = mockery.named_mock('named_mock')
assert_equal "#<Mock:named_mock>", mock.mocha_inspect
end
def test_should_display_name_for_mocha_inspect_if_mock_has_symbol_name
mockery = Mockery.new
mock = mockery.named_mock(:named_mock)
assert_equal "#<Mock:named_mock>", mock.mocha_inspect
end
def test_should_display_name_for_inspect_if_mock_has_string_name
mockery = Mockery.new
mock = mockery.named_mock('named_mock')
assert_equal "#<Mock:named_mock>", mock.inspect
end
def test_should_display_name_for_inspect_if_mock_has_symbol_name
mockery = Mockery.new
mock = mockery.named_mock(:named_mock)
assert_equal "#<Mock:named_mock>", mock.inspect
end
def test_should_display_impersonated_object_for_mocha_inspect
mockery = Mockery.new
instance = Object.new
mock = mockery.mock_impersonating(instance)
assert_equal "#{instance.mocha_inspect}", mock.mocha_inspect
end
def test_should_display_impersonated_object_for_inspect
mockery = Mockery.new
instance = Object.new
mock = mockery.mock_impersonating(instance)
assert_equal "#{instance.mocha_inspect}", mock.inspect
end
class FakeClass; end
def test_should_display_any_instance_prefix_followed_by_class_whose_instances_are_being_impersonated_for_mocha_inspect
mockery = Mockery.new
mock = mockery.mock_impersonating_any_instance_of(FakeClass)
assert_equal "#<AnyInstance:MockeryTest::FakeClass>", mock.mocha_inspect
end
def test_should_display_any_instance_prefix_followed_by_class_whose_instances_are_being_impersonated_for_inspect
mockery = Mockery.new
mock = mockery.mock_impersonating_any_instance_of(FakeClass)
assert_equal "#<AnyInstance:MockeryTest::FakeClass>", mock.inspect
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/scanner.rb
|
#
# scanner.rb
#
# Copyright (c) 1998-2003 <NAME> <<EMAIL>>
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2 or later.
#
require 'tmail/utils'
module TMail
require 'tmail/scanner_r.rb'
begin
raise LoadError, 'Turn off Ruby extention by user choice' if ENV['NORUBYEXT']
require 'tmail/scanner_c.so'
Scanner = Scanner_C
rescue LoadError
Scanner = Scanner_R
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/lib/webrick_server.rb
|
# Donated by <NAME>
require 'webrick'
require 'cgi'
require 'stringio'
include WEBrick
class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
REQUEST_MUTEX = Mutex.new
def self.dispatch(options = {})
Socket.do_not_reverse_lookup = true # patch for OS X
server = WEBrick::HTTPServer.new(:Port => options[:port].to_i, :ServerType => options[:server_type], :BindAddress => options[:ip])
server.mount('/', DispatchServlet, options)
trap("INT") { server.shutdown }
server.start
end
def initialize(server, options)
@server_options = options
@file_handler = WEBrick::HTTPServlet::FileHandler.new(server, options[:server_root])
super
end
def do_GET(req, res)
begin
unless handle_index(req, res)
unless handle_dispatch(req, res)
unless handle_file(req, res)
REQUEST_MUTEX.lock
unless handle_mapped(req, res)
raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
end
end
end
end
ensure
REQUEST_MUTEX.unlock if REQUEST_MUTEX.locked?
end
end
alias :do_POST :do_GET
def handle_index(req, res)
if req.request_uri.path == "/"
if @server_options[:index_controller]
res.set_redirect WEBrick::HTTPStatus::MovedPermanently, "/#{@server_options[:index_controller]}/"
else
res.set_redirect WEBrick::HTTPStatus::MovedPermanently, "/_doc/"
end
return true
else
return false
end
end
def handle_file(req, res)
begin
@file_handler.send(:do_GET, req, res)
return true
rescue HTTPStatus::PartialContent, HTTPStatus::NotModified => err
res.set_error(err)
return true
rescue => err
return false
end
end
def handle_mapped(req, res)
if mappings = DispatchServlet.parse_uri(req.request_uri.path)
query = mappings.collect { |pair| "#{pair.first}=#{pair.last}" }.join("&")
query << "&#{req.request_uri.query}" if req.request_uri.query
origin = req.request_uri.path + "?" + query
req.request_uri.path = "/dispatch.rb"
req.request_uri.query = query
handle_dispatch(req, res, origin)
else
return false
end
end
def handle_dispatch(req, res, origin = nil)
return false unless /^\/dispatch\.(?:cgi|rb|fcgi)$/.match(req.request_uri.path)
env = req.meta_vars.clone
env["QUERY_STRING"] = req.request_uri.query
env["REQUEST_URI"] = origin if origin
data = nil
$old_stdin, $old_stdout = $stdin, $stdout
$stdin, $stdout = StringIO.new(req.body || ""), StringIO.new
begin
require 'cgi'
CGI.send(:define_method, :env_table) { env }
load File.join(@server_options[:server_root], "dispatch.rb")
$stdout.rewind
data = $stdout.read
ensure
$stdin, $stdout = $old_stdin, $old_stdout
end
raw_header, body = *data.split(/^[\xd\xa]+/on, 2)
header = WEBrick::HTTPUtils::parse_header(raw_header)
if /^(\d+)/ =~ header['status'][0]
res.status = $1.to_i
header.delete('status')
end
header.each { |key, val| res[key] = val.join(", ") }
res.body = body
return true
rescue => err
p err, err.backtrace
return false
end
def self.parse_uri(path)
component, id = /([-_a-zA-Z0-9]+)/, /([0-9]+)/
case path.sub(%r{^/(?:fcgi|mruby|cgi)/}, "/")
when %r{^/#{component}/?$} then
{ :controller => $1, :action => "index" }
when %r{^/#{component}/#{component}$} then
{ :controller => $1, :action => $2 }
when %r{^/#{component}/#{component}/#{id}$} then
{ :controller => $1, :action => $2, :id => $3 }
when %r{^/#{component}/#{component}/$} then
{ :module => $1, :controller => $2, :action => "index" }
when %r{^/#{component}/#{component}/#{component}$} then
if DispatchServlet.modules(component).include?($1)
{ :module => $1, :controller => $2, :action => $3 }
else
{ :controller => $1, :action => $2, :id => $3 }
end
when %r{^/#{component}/#{component}/#{component}/#{id}$} then
{ :module => $1, :controller => $2, :action => $3, :id => $4 }
else
false
end
end
def self.modules(module_pattern = '[^.]+')
path = RAILS_ROOT + '/app/controllers'
Dir.entries(path).grep(/^#{module_pattern}$/).find_all {|e| File.directory?("#{path}/#{e}")}
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/shoulda-matchers-1.4.2/lib/shoulda/matchers/independent/delegate_matcher.rb
|
require 'bourne'
module Shoulda # :nodoc:
module Matchers
module Independent # :nodoc:
# Ensure that a given method is delegated properly.
#
# Basic Syntax:
# it { should delegate_method(:deliver_mail).to(:mailman) }
#
# Options:
# * <tt>:as</tt> - tests that the object being delegated to is called with a certain method (defaults to same name as delegating method)
# * <tt>:with_arguments</tt> - tests that the method on the object being delegated to is called with certain arguments
#
# Examples:
# it { should delegate_method(:deliver_mail).to(:mailman).as(:deliver_with_haste)
# it { should delegate_method(:deliver_mail).to(:mailman).with_arguments('221B Baker St.', :hastily => true)
#
def delegate_method(delegating_method)
DelegateMatcher.new(delegating_method)
end
class DelegateMatcher
def initialize(delegating_method)
@delegating_method = delegating_method
end
def matches?(subject)
@subject = subject
ensure_target_method_is_present!
begin
extend Mocha::API
stubbed_object = stub(method_on_target)
subject.stubs(@target_method).returns(stubbed_object)
subject.send(@delegating_method)
stubbed_object.should have_received(method_on_target).with(*@delegated_arguments)
rescue NoMethodError, RSpec::Expectations::ExpectationNotMetError, Mocha::ExpectationError
false
end
end
def does_not_match?(subject)
raise InvalidDelegateMatcher
end
def to(target_method)
@target_method = target_method
self
end
def as(method_on_target)
@method_on_target = method_on_target
self
end
def with_arguments(*arguments)
@delegated_arguments = arguments
self
end
def failure_message
base = "Expected #{delegating_method_name} to delegate to #{target_method_name}"
add_clarifications_to(base)
end
private
def add_clarifications_to(message)
if @delegated_arguments.present?
message << " with arguments: #{@delegated_arguments.inspect}"
end
if @method_on_target.present?
message << " as :#{@method_on_target}"
end
message
end
def delegating_method_name
method_name_with_class(@delegating_method)
end
def target_method_name
method_name_with_class(@target_method)
end
def method_name_with_class(method)
if Class === @subject
@subject.name + '.' + method.to_s
else
@subject.class.name + '#' + method.to_s
end
end
def method_on_target
@method_on_target || @delegating_method
end
def ensure_target_method_is_present!
if @target_method.blank?
raise TargetNotDefinedError
end
end
end
class DelegateMatcher::TargetNotDefinedError < StandardError
def message
'Delegation needs a target. Use the #to method to define one, e.g. `post_office.should delegate(:deliver_mail).to(:mailman)`'
end
end
class DelegateMatcher::InvalidDelegateMatcher < StandardError
def message
'#delegate_to does not support #should_not syntax.'
end
end
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/base64.rb
|
#
# base64.rb
#
# Copyright (c) 1998-2003 <NAME> <<EMAIL>>
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2 or later.
#
module TMail
module Base64
module_function
def rb_folding_encode( str, eol = "\n", limit = 60 )
[str].pack('m')
end
def rb_encode( str )
[str].pack('m').tr( "\r\n", '' )
end
def rb_decode( str, strict = false )
str.unpack('m')
end
begin
require 'tmail/base64.so'
alias folding_encode c_folding_encode
alias encode c_encode
alias decode c_decode
class << self
alias folding_encode c_folding_encode
alias encode c_encode
alias decode c_decode
end
rescue LoadError
alias folding_encode rb_folding_encode
alias encode rb_encode
alias decode rb_decode
class << self
alias folding_encode rb_folding_encode
alias encode rb_encode
alias decode rb_decode
end
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/generators/scaffold/templates/controller.rb
|
<gh_stars>1-10
class <%= @controller_class_name %>Controller < ApplicationController
<% unless suffix -%>
def index
list
render_action 'list'
end
<% end -%>
<% for action in unscaffolded_actions -%>
def <%= action %><%= suffix %>
end
<% end -%>
def list<%= suffix %>
@<%= plural_name %> = <%= class_name %>.find_all
end
def show<%= suffix %>
@<%= singular_name %> = <%= class_name %>.find(@params['id'])
end
def new<%= suffix %>
@<%= singular_name %> = <%= class_name %>.new
end
def create<%= suffix %>
@<%= singular_name %> = <%= class_name %>.new(@params['<%= singular_name %>'])
if @<%= singular_name %>.save
flash['notice'] = '<%= class_name %> was successfully created.'
redirect_to :action => 'list<%= suffix %>'
else
render_action 'new<%= suffix %>'
end
end
def edit<%= suffix %>
@<%= singular_name %> = <%= class_name %>.find(@params['id'])
end
def update
@<%= singular_name %> = <%= class_name %>.find(@params['<%= singular_name %>']['id'])
if @<%= singular_name %>.update_attributes(@params['<%= singular_name %>'])
flash['notice'] = '<%= class_name %> was successfully updated.'
redirect_to :action => 'show<%= suffix %>', :id => @<%= singular_name %>.id
else
render_action 'edit<%= suffix %>'
end
end
def destroy<%= suffix %>
<%= class_name %>.find(@params['id']).destroy
redirect_to :action => 'list<%= suffix %>'
end
end
|
beno/devise_sociable
|
test/test_helper.rb
|
<filename>test/test_helper.rb
require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'support'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'test/unit'
require 'active_record'
require 'mocha'
require 'helpers'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
class Migration < ActiveRecord::Migration
def up
create_table :sessions do |t|
t.string :session_id, :null => false
t.text :data
t.timestamps
end
create_table :users do |t|
t.string :email
t.string :last_request_at
t.string :last_sign_out_at
t.timestamps
end
end
end
Migration.new.up
require 'devise'
require 'devise/orm/active_record'
require 'devise_sociable'
class User < ActiveRecord::Base
devise :sociable
end
|
beno/devise_sociable
|
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/facade.rb
|
<reponame>beno/devise_sociable
#
# facade.rb
#
# Copyright (c) 1998-2003 <NAME> <<EMAIL>>
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2 or later.
#
require 'tmail/utils'
module TMail
class Mail
def header_string( name, default = nil )
h = @header[name.downcase] or return default
h.to_s
end
###
### attributes
###
include TextUtils
def set_string_array_attr( key, strs )
strs.flatten!
if strs.empty?
@header.delete key.downcase
else
store key, strs.join(', ')
end
strs
end
private :set_string_array_attr
def set_string_attr( key, str )
if str
store key, str
else
@header.delete key.downcase
end
str
end
private :set_string_attr
def set_addrfield( name, arg )
if arg
h = HeaderField.internal_new(name, @config)
h.addrs.replace [arg].flatten
@header[name] = h
else
@header.delete name
end
arg
end
private :set_addrfield
def addrs2specs( addrs )
return nil unless addrs
list = addrs.map {|addr|
if addr.address_group?
then addr.map {|a| a.spec }
else addr.spec
end
}.flatten
return nil if list.empty?
list
end
private :addrs2specs
#
# date time
#
def date( default = nil )
if h = @header['date']
h.date
else
default
end
end
def date=( time )
if time
store 'Date', time2str(time)
else
@header.delete 'date'
end
time
end
def strftime( fmt, default = nil )
if t = date
t.strftime(fmt)
else
default
end
end
#
# destination
#
def to_addrs( default = nil )
if h = @header['to']
h.addrs
else
default
end
end
def cc_addrs( default = nil )
if h = @header['cc']
h.addrs
else
default
end
end
def bcc_addrs( default = nil )
if h = @header['bcc']
h.addrs
else
default
end
end
def to_addrs=( arg )
set_addrfield 'to', arg
end
def cc_addrs=( arg )
set_addrfield 'cc', arg
end
def bcc_addrs=( arg )
set_addrfield 'bcc', arg
end
def to( default = nil )
addrs2specs(to_addrs(nil)) || default
end
def cc( default = nil )
addrs2specs(cc_addrs(nil)) || default
end
def bcc( default = nil )
addrs2specs(bcc_addrs(nil)) || default
end
def to=( *strs )
set_string_array_attr 'To', strs
end
def cc=( *strs )
set_string_array_attr 'Cc', strs
end
def bcc=( *strs )
set_string_array_attr 'Bcc', strs
end
#
# originator
#
def from_addrs( default = nil )
if h = @header['from']
h.addrs
else
default
end
end
def from_addrs=( arg )
set_addrfield 'from', arg
end
def from( default = nil )
addrs2specs(from_addrs(nil)) || default
end
def from=( *strs )
set_string_array_attr 'From', strs
end
def friendly_from( default = nil )
h = @header['from']
a, = h.addrs
return default unless a
return a.phrase if a.phrase
return h.comments.join(' ') unless h.comments.empty?
a.spec
end
def reply_to_addrs( default = nil )
if h = @header['reply-to']
h.addrs
else
default
end
end
def reply_to_addrs=( arg )
set_addrfield 'reply-to', arg
end
def reply_to( default = nil )
addrs2specs(reply_to_addrs(nil)) || default
end
def reply_to=( *strs )
set_string_array_attr 'Reply-To', strs
end
def sender_addr( default = nil )
f = @header['sender'] or return default
f.addr or return default
end
def sender_addr=( addr )
if addr
h = HeaderField.internal_new('sender', @config)
h.addr = addr
@header['sender'] = h
else
@header.delete 'sender'
end
addr
end
def sender( default )
f = @header['sender'] or return default
a = f.addr or return default
a.spec
end
def sender=( str )
set_string_attr 'Sender', str
end
#
# subject
#
def subject( default = nil )
if h = @header['subject']
h.body
else
default
end
end
def subject=( str )
set_string_attr 'Subject', str
end
#
# identity & threading
#
def message_id( default = nil )
if h = @header['message-id']
h.id || default
else
default
end
end
def message_id=( str )
set_string_attr 'Message-Id', str
end
def in_reply_to( default = nil )
if h = @header['in-reply-to']
h.ids
else
default
end
end
def in_reply_to=( *idstrs )
set_string_array_attr 'In-Reply-To', idstrs
end
def references( default = nil )
if h = @header['references']
h.refs
else
default
end
end
def references=( *strs )
set_string_array_attr 'References', strs
end
#
# MIME headers
#
def mime_version( default = nil )
if h = @header['mime-version']
h.version || default
else
default
end
end
def mime_version=( m, opt = nil )
if opt
if h = @header['mime-version']
h.major = m
h.minor = opt
else
store 'Mime-Version', "#{m}.#{opt}"
end
else
store 'Mime-Version', m
end
m
end
def content_type( default = nil )
if h = @header['content-type']
h.content_type || default
else
default
end
end
def main_type( default = nil )
if h = @header['content-type']
h.main_type || default
else
default
end
end
def sub_type( default = nil )
if h = @header['content-type']
h.sub_type || default
else
default
end
end
def set_content_type( str, sub = nil, param = nil )
if sub
main, sub = str, sub
else
main, sub = str.split(%r</>, 2)
raise ArgumentError, "sub type missing: #{str.inspect}" unless sub
end
if h = @header['content-type']
h.main_type = main
h.sub_type = sub
h.params.clear
else
store 'Content-Type', "#{main}/#{sub}"
end
@header['content-type'].params.replace param if param
str
end
alias content_type= set_content_type
def type_param( name, default = nil )
if h = @header['content-type']
h[name] || default
else
default
end
end
def charset( default = nil )
if h = @header['content-type']
h['charset'] or default
else
default
end
end
def charset=( str )
if str
if h = @header[ 'content-type' ]
h['charset'] = str
else
store 'Content-Type', "text/plain; charset=#{str}"
end
end
str
end
def transfer_encoding( default = nil )
if h = @header['content-transfer-encoding']
h.encoding || default
else
default
end
end
def transfer_encoding=( str )
set_string_attr 'Content-Transfer-Encoding', str
end
alias encoding transfer_encoding
alias encoding= transfer_encoding=
alias content_transfer_encoding transfer_encoding
alias content_transfer_encoding= transfer_encoding=
def disposition( default = nil )
if h = @header['content-disposition']
h.disposition || default
else
default
end
end
alias content_disposition disposition
def set_disposition( str, params = nil )
if h = @header['content-disposition']
h.disposition = str
h.params.clear
else
h = store('Content-Disposition', str)
end
h.params.replace params if params
end
alias disposition= set_disposition
alias set_content_disposition set_disposition
alias content_disposition= set_disposition
def disposition_param( name, default = nil )
if h = @header['content-disposition']
h[name] || default
else
default
end
end
###
### utils
###
def create_reply
mail = TMail::Mail.parse('')
mail.subject = 'Re: ' + subject('').sub(/\A(?:\[[^\]]+\])?(?:\s*Re:)*\s*/i, '')
mail.to_addrs = reply_addresses([])
mail.in_reply_to = [message_id(nil)].compact
mail.references = references([]) + [message_id(nil)].compact
mail.mime_version = '1.0'
mail
end
def base64_encode
store 'Content-Transfer-Encoding', 'Base64'
self.body = Base64.folding_encode(self.body)
end
def base64_decode
if /base64/i === self.transfer_encoding('')
store 'Content-Transfer-Encoding', '8bit'
self.body = Base64.decode(self.body, @config.strict_base64decode?)
end
end
def destinations( default = nil )
ret = []
%w( to cc bcc ).each do |nm|
if h = @header[nm]
h.addrs.each {|i| ret.push i.address }
end
end
ret.empty? ? default : ret
end
def each_destination( &block )
destinations([]).each do |i|
if Address === i
yield i
else
i.each(&block)
end
end
end
alias each_dest each_destination
def reply_addresses( default = nil )
reply_to_addrs(nil) or from_addrs(nil) or default
end
def error_reply_addresses( default = nil )
if s = sender(nil)
[s]
else
from_addrs(default)
end
end
def multipart?
main_type('').downcase == 'multipart'
end
end # class Mail
end # module TMail
|
beno/devise_sociable
|
vendor/bundle/gems/bourne-1.1.2/bourne.gemspec
|
<reponame>beno/devise_sociable<filename>vendor/bundle/gems/bourne-1.1.2/bourne.gemspec
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "bourne/version"
Gem::Specification.new do |s|
s.name = 'bourne'
s.version = Bourne::VERSION.dup
s.platform = Gem::Platform::RUBY
s.authors = ["<NAME>"]
s.email = '<EMAIL>'
s.homepage = 'http://github.com/thoughtbot/bourne'
s.summary = 'Adds test spies to mocha.'
s.description = %q{Extends mocha to allow detailed tracking and querying of
stub and mock invocations. Allows test spies using the have_received rspec
matcher and assert_received for Test::Unit. Extracted from the
jferris-mocha fork.}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency('mocha', '= 0.10.5')
s.add_development_dependency('rake')
end
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/environments/production.rb
|
Dependencies.mechanism = :require
ActionController::Base.consider_all_requests_local = false
ActionController::Base.perform_caching = true
|
beno/devise_sociable
|
vendor/bundle/specifications/tzinfo-0.3.35.gemspec
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "tzinfo"
s.version = "0.3.35"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["<NAME>"]
s.date = "2012-11-04"
s.description = "TZInfo is a Ruby library that uses the standard tz (Olson) database to provide daylight savings aware transformations between times in different time zones."
s.email = "<EMAIL>"
s.extra_rdoc_files = ["README", "CHANGES"]
s.files = ["README", "CHANGES"]
s.homepage = "http://tzinfo.rubyforge.org/"
s.rdoc_options = ["--exclude", "definitions", "--exclude", "indexes"]
s.require_paths = ["lib"]
s.rubyforge_project = "tzinfo"
s.rubygems_version = "1.8.23"
s.summary = "Daylight-savings aware timezone library"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/actionmailer-0.6.1/lib/action_mailer/vendor/tmail/address.rb
|
<gh_stars>1-10
#
# address.rb
#
# Copyright (c) 1998-2003 <NAME> <<EMAIL>>
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2 or later.
#
require 'tmail/encode'
require 'tmail/parser'
module TMail
class Address
include TextUtils
def Address.parse( str )
Parser.parse :ADDRESS, str
end
def address_group?
false
end
def initialize( local, domain )
if domain
domain.each do |s|
raise SyntaxError, 'empty word in domain' if s.empty?
end
end
@local = local
@domain = domain
@name = nil
@routes = []
end
attr_reader :name
def name=( str )
@name = str
@name = nil if str and str.empty?
end
alias phrase name
alias phrase= name=
attr_reader :routes
def inspect
"#<#{self.class} #{address()}>"
end
def local
return nil unless @local
return '""' if @local.size == 1 and @local[0].empty?
@local.map {|i| quote_atom(i) }.join('.')
end
def domain
return nil unless @domain
join_domain(@domain)
end
def spec
s = self.local
d = self.domain
if s and d
s + '@' + d
else
s
end
end
alias address spec
def ==( other )
other.respond_to? :spec and self.spec == other.spec
end
alias eql? ==
def hash
@local.hash ^ @domain.hash
end
def dup
obj = self.class.new(@local.dup, @domain.dup)
obj.name = @name.dup if @name
obj.routes.replace @routes
obj
end
include StrategyInterface
def accept( strategy, dummy1 = nil, dummy2 = nil )
unless @local
strategy.meta '<>' # empty return-path
return
end
spec_p = (not @name and @routes.empty?)
if @name
strategy.phrase @name
strategy.space
end
tmp = spec_p ? '' : '<'
unless @routes.empty?
tmp << @routes.map {|i| '@' + i }.join(',') << ':'
end
tmp << self.spec
tmp << '>' unless spec_p
strategy.meta tmp
strategy.lwsp ''
end
end
class AddressGroup
include Enumerable
def address_group?
true
end
def initialize( name, addrs )
@name = name
@addresses = addrs
end
attr_reader :name
def ==( other )
other.respond_to? :to_a and @addresses == other.to_a
end
alias eql? ==
def hash
map {|i| i.hash }.hash
end
def []( idx )
@addresses[idx]
end
def size
@addresses.size
end
def empty?
@addresses.empty?
end
def each( &block )
@addresses.each(&block)
end
def to_a
@addresses.dup
end
alias to_ary to_a
def include?( a )
@addresses.include? a
end
def flatten
set = []
@addresses.each do |a|
if a.respond_to? :flatten
set.concat a.flatten
else
set.push a
end
end
set
end
def each_address( &block )
flatten.each(&block)
end
def add( a )
@addresses.push a
end
alias push add
def delete( a )
@addresses.delete a
end
include StrategyInterface
def accept( strategy, dummy1 = nil, dummy2 = nil )
strategy.phrase @name
strategy.meta ':'
strategy.space
first = true
each do |mbox|
if first
first = false
else
strategy.meta ','
end
strategy.space
mbox.accept strategy
end
strategy.meta ';'
strategy.lwsp ''
end
end
end # module TMail
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/generators/mailer/mailer_generator.rb
|
<filename>vendor/bundle/gems/rails-0.9.5/generators/mailer/mailer_generator.rb
require 'rails_generator'
class MailerGenerator < Rails::Generator::Base
attr_reader :actions
def generate
@actions = args
# Mailer class and unit test.
template "mailer.rb", "app/models/#{file_name}.rb"
template "unit_test.rb", "test/unit/#{file_name}_test.rb"
# Test fixtures directory.
FileUtils.mkdir_p "test/fixtures/#{table_name}"
# View template and fixture for each action.
args.each do |action|
template "view.rhtml", "app/views/#{file_name}/#{action}.rhtml", binding
template "fixture.rhtml", "test/fixtures/#{table_name}/#{action}", binding
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/mocha-0.10.5/lib/mocha/parameter_matchers/has_entry.rb
|
<gh_stars>1-10
require 'mocha/parameter_matchers/base'
module Mocha
module ParameterMatchers
# :call-seq: has_entry(key, value) -> parameter_matcher
# has_entry(key => value) -> parameter_matcher
#
# Matches +Hash+ containing entry with +key+ and +value+.
# object = mock()
# object.expects(:method_1).with(has_entry('key_1', 1))
# object.method_1('key_1' => 1, 'key_2' => 2)
# # no error raised
#
# object = mock()
# object.expects(:method_1).with(has_entry('key_1' => 1))
# object.method_1('key_1' => 1, 'key_2' => 2)
# # no error raised
#
# object = mock()
# object.expects(:method_1).with(has_entry('key_1', 1))
# object.method_1('key_1' => 2, 'key_2' => 1)
# # error raised, because method_1 was not called with Hash containing entry: 'key_1' => 1
#
# object = mock()
# object.expects(:method_1).with(has_entry('key_1' => 1))
# object.method_1('key_1' => 2, 'key_2' => 1)
# # error raised, because method_1 was not called with Hash containing entry: 'key_1' => 1
def has_entry(*options)
key, value = options.shift, options.shift
if key.is_a?(Hash)
case key.length
when 0
raise ArgumentError.new("Argument has no entries.")
when 1
key, value = key.to_a.flatten
else
raise ArgumentError.new("Argument has multiple entries. Use Mocha::ParameterMatchers#has_entries instead.")
end
end
HasEntry.new(key, value)
end
class HasEntry < Base # :nodoc:
def initialize(key, value)
@key, @value = key, value
end
def matches?(available_parameters)
parameter = available_parameters.shift
return false unless parameter.respond_to?(:keys) && parameter.respond_to?(:[])
matching_keys = parameter.keys.select { |key| @key.to_matcher.matches?([key]) }
matching_keys.any? { |key| @value.to_matcher.matches?([parameter[key]]) }
end
def mocha_inspect
"has_entry(#{@key.mocha_inspect} => #{@value.mocha_inspect})"
end
end
end
end
|
beno/devise_sociable
|
vendor/bundle/gems/rails-0.9.5/generators/scaffold/scaffold_generator.rb
|
<filename>vendor/bundle/gems/rails-0.9.5/generators/scaffold/scaffold_generator.rb
require 'rails_generator'
class ScaffoldGenerator < Rails::Generator::Base
def generate
# Model.
generator('model').generate
# Fixtures.
template "fixtures.yml", "test/fixtures/#{table_name}.yml"
@controller_class_name = args.empty? ? Inflector.pluralize(class_name) : args.shift.sub(/^[a-z]?/) { |m| m.capitalize }
@controller_name = Inflector.underscore(@controller_class_name)
# Controller class, functional test, helper, and views.
template "controller.rb", "app/controllers/#{@controller_name}_controller.rb"
template "functional_test.rb", "test/functional/#{@controller_name}_controller_test.rb"
template "controller/helper.rb", "app/helpers/#{@controller_name}_helper.rb"
# Layout and stylesheet.
unless File.file?("app/views/layouts/#{@controller_name}.rhtml")
template "layout.rhtml", "app/views/layouts/#{@controller_name}.rhtml"
end
unless File.file?("public/stylesheets/scaffold.css")
template "style.css", "public/stylesheets/scaffold.css"
end
# Scaffolded views.
scaffold_views.each do |action|
template "view_#{action}.rhtml", "app/views/#{@controller_name}/#{action}.rhtml"
end
# Unscaffolded views.
unscaffolded_actions.each do |action|
template "controller/view.rhtml",
"app/views/#{@controller_name}/#{action}.rhtml",
binding
end
end
def full_class_name
class_name + "Controller"
end
protected
def scaffold_views
%w(list show new edit)
end
def scaffold_actions
scaffold_views + %w(index create update destroy)
end
def unscaffolded_actions
args - scaffold_actions
end
def suffix
"_#{singular_name}" if options[:suffix]
end
end
|
tongueroo/forger
|
lib/forger/cleaner/ami.rb
|
module Forger::Cleaner
class Ami < Forger::Base
include Forger::AwsServices
def clean
query = @options[:query]
keep = @options[:keep] || 2
puts "Cleaning out old AMIs with base name: #{@options[:query]}"
return if ENV['TEST']
images = search_ami(query)
images = images.sort_by { |i| i.name }.reverse
delete_list = images[keep..-1] || []
puts "Deleting #{delete_list.size} images."
delete_list.each do |i|
delete(i)
end
end
private
def delete(image)
message = "Deleting image: #{image.image_id} #{image.name}"
if @options[:noop]
puts "NOOP: #{message}"
else
puts message
ec2.deregister_image(image_id: image.image_id)
end
rescue Aws::EC2::Errors::InvalidAMIIDUnavailable
# happens when image was just deleted but its still
# showing up as available when calling describe_images
puts "WARN: #{e.message}"
end
def search_ami(query, owners=["self"])
ec2.describe_images(
owners: owners,
filters: [
{name: "name", values: [query]},
{name: "state", values: ["available"]}
]
).images
end
end
end
|
tongueroo/forger
|
lib/forger/create/error_messages.rb
|
<gh_stars>1-10
require "active_support/core_ext/string"
class Forger::Create
module ErrorMessages
def handle_ec2_service_error!(exception)
meth = map_exception_to_method(exception)
if respond_to?(meth)
message = send(meth) # custom specific error message
message = print_error_message(exception, message)
else
# generic error message
print_error_message(exception, <<-EOL)
There was an error with the parameters used for the run_instance method.
EOL
end
end
# Examples:
# Aws::EC2::Errors::InvalidGroupNotFound => invalid_group_not_found
# Aws::EC2::Errors::InvalidParameterCombination => invalid_parameter_combination
def map_exception_to_method(exception)
class_name = File.basename(exception.class.to_s).sub(/.*::/,'')
class_name.underscore # method_name
end
def print_error_message(exception, message)
puts "ERROR: Unable to launch the instance.".color(:red)
puts message
puts exception.message
puts "For the full internal backtrace re-run the command with DEBUG=1"
puts exception.backtrace if ENV['DEBUG']
exit 1
end
#######################################################
# specific messages with a little more info for more common error cases below:
def invalid_group_not_found
<<-EOL
The security group passed in does not exit.
Please double check that security group exists in the VPC.
EOL
end
def invalid_parameter_combination
<<-EOL
The parameters passed to the run_instances method were invalid.
Please double check that the parameters are all valid.
EOL
end
def invalid_subnet_id_not_found
<<-EOL
The provided subnets ids were were not found.
Please double check that the subnets exists.
EOL
end
end
end
|
tongueroo/forger
|
lib/forger/cli.rb
|
<reponame>tongueroo/forger<filename>lib/forger/cli.rb
module Forger
class CLI < Command
class_option :noop, type: :boolean
class_option :profile, desc: "profile name to use"
desc "clean SUBCOMMAND", "clean subcommands"
long_desc Help.text(:clean)
subcommand "clean", Clean
desc "wait SUBCOMMAND", "wait subcommands"
long_desc Help.text(:wait)
subcommand "wait", Wait
common_options = Proc.new do
option :auto_terminate, type: :boolean, default: false, desc: "automatically terminate the instance at the end of user-data"
option :cloudwatch, type: :boolean, desc: "enable cloudwatch logging, supported for amazonlinux2 and ubuntu"
option :ami_name, desc: "when specified, an ami creation script is appended to the user-data script"
option :randomize, type: :boolean, desc: "append random characters to end of name"
option :source_ami, desc: "override the source image_id in profile"
option :wait, type: :boolean, default: true, desc: "Wait until the instance is ready and report dns name"
option :ssh, type: :boolean, desc: "Ssh into instance immediately after it's ready"
option :ssh_user, default: "ec2-user", desc: "User to use to with the ssh option to log into instance"
end
long_desc Help.text(:new)
New.cli_options.each do |args|
option(*args)
end
register(New, "new", "new NAME", "Generates new forger project")
desc "create NAME", "create ec2 instance"
long_desc Help.text(:create)
common_options.call
def create(name)
Create.new(options.merge(name: name)).run
end
desc "ami NAME", "launches instance and uses it create AMI"
long_desc Help.text(:ami)
common_options.call
def ami(name)
Ami.new(options.merge(name: name)).run
end
desc "compile", "compiles app/scripts and app/user_data to tmp folder"
long_desc Help.text(:compile)
option :layout, default: "default", desc: "layout for user_data helper"
def compile
Script::Compile.new(options).compile_all
end
desc "upload", "compiles and uploads scripts to s3"
long_desc Help.text(:upload)
option :compile, type: :boolean, default: true, desc: "compile scripts before uploading"
def upload
Script::Upload.new(options).upload
end
desc "destroy", "Destroys instance accounting for spot request"
long_desc Help.text("destroy")
def destroy(instance_id)
Destroy.new(options).run(instance_id)
end
desc "completion *PARAMS", "Prints words for auto-completion."
long_desc Help.text("completion")
def completion(*params)
Completer.new(CLI, *params).run
end
desc "completion_script", "Generates a script that can be eval to setup auto-completion."
long_desc Help.text("completion_script")
def completion_script
Completer::Script.generate
end
desc "version", "prints version"
def version
puts VERSION
end
desc "s3 SUBCOMMAND", "s3 subcommands"
long_desc Help.text(:s3)
subcommand "s3", S3
end
end
|
tongueroo/forger
|
lib/forger/script/compile.rb
|
<gh_stars>1-10
require 'fileutils'
# Class for forger compile command
class Forger::Script
class Compile < Forger::Base
include Forger::Template
# used in upload
def compile_scripts
clean
compile_folder("scripts")
end
# use in compile cli command
def compile_all
clean
compile_folder("scripts")
layout_path = context.layout_path(@options[:layout])
compile_folder("user-data", layout_path)
end
def compile_folder(folder, layout_path=false)
puts "Compiling app/#{folder} to tmp/app/#{folder}.".color(:green)
Dir.glob("#{Forger.root}/app/#{folder}/**/*").each do |path|
next if File.directory?(path)
next if path.include?("layouts")
result = RenderMePretty.result(path, layout: layout_path, context: context)
tmp_path = path.sub(%r{.*/app/}, "#{BUILD_ROOT}/app/")
puts " #{tmp_path}" if @options[:verbose]
FileUtils.mkdir_p(File.dirname(tmp_path))
IO.write(tmp_path, result)
end
end
def clean
FileUtils.rm_rf("#{BUILD_ROOT}/app")
end
end
end
|
tongueroo/forger
|
lib/forger/create/params.rb
|
<gh_stars>1-10
class Forger::Create
class Params < Forger::Base
# deep_symbolize_keys is ran at the very end only.
# up until that point we're dealing with String keys.
def generate
cleanup
params = Forger::Profile.new(@options).load
decorate_params(params)
normalize_launch_template(params).deep_symbolize_keys
end
def decorate_params(params)
upsert_name_tag!(params)
replace_runtime_options!(params)
params
end
# Expose a list of runtime params that are convenient. Try to limit the
# number of options from the cli to keep tool simple. Most options can
# be easily control through profile files. The runtime options that are
# very convenient to have at the CLI are modified here.
def replace_runtime_options!(params)
params["image_id"] = @options[:source_ami_id] if @options[:source_ami_id]
params
end
def cleanup
FileUtils.rm_f("#{Forger.root}/tmp/user-data.txt")
end
# Adds instance ec2 tag if not already provided
def upsert_name_tag!(params)
specs = params["tag_specifications"] || []
# insert an empty spec placeholder if one not found
spec = specs.find do |s|
s["resource_type"] == "instance"
end
unless spec
spec = {
"resource_type" => "instance",
"tags" => []
}
specs << spec
end
# guaranteed there's a tag_specifications with resource_type instance at this point
tags = spec["tags"] || []
unless tags.map { |t| t["key"] }.include?("Name")
tags << { "key" => "Name", "value" => @name }
end
specs = specs.map do |s|
# replace the name tag value
if s["resource_type"] == "instance"
{
"resource_type" => "instance",
"tags" => tags
}
else
s
end
end
params["tag_specifications"] = specs
params
end
# Allow adding launch template as a simple string.
#
# Standard structure:
# {
# launch_template: { launch_template_name: "TestLaunchTemplate" },
# }
#
# Simple string:
# {
# launch_template: "TestLaunchTemplate",
# }
#
# When launch_template is a simple String it will get transformed to the
# standard structure.
def normalize_launch_template(params)
if params["launch_template"].is_a?(String)
launch_template_identifier = params["launch_template"]
launch_template = if launch_template_identifier =~ /^lt-/
{ "launch_template_id" => launch_template_identifier }
else
{ "launch_template_name" => launch_template_identifier }
end
params["launch_template"] = launch_template
end
params
end
# Hard coded sensible defaults.
# Can be overridden easily with profiles
def defaults
{
max_count: 1,
min_count: 1,
}
end
end
end
|
tongueroo/forger
|
lib/forger/aws_services.rb
|
require 'aws-sdk-cloudformation'
require 'aws-sdk-ec2'
require 'aws-sdk-s3'
module Forger::AwsServices
extend Memoist
def cfn
Aws::CloudFormation::Client.new
end
memoize :cfn
def ec2
Aws::EC2::Client.new
end
memoize :ec2
def s3
Aws::S3::Client.new
end
memoize :s3
end
|
tongueroo/forger
|
spec/fixtures/demo_project/config/variables/test.rb
|
<reponame>tongueroo/forger<filename>spec/fixtures/demo_project/config/variables/test.rb<gh_stars>1-10
@subnets = %w[subnet-111 subnet-222]
@security_group_ids = %w[sg-111]
@test_key = ENV['TEST_KEY']
|
tongueroo/forger
|
lib/forger/core.rb
|
require 'pathname'
require 'yaml'
module Forger
module Core
extend Memoist
def settings
Setting.new.data
end
# cloudwatch cli option takes higher precedence than when its set in the
# config/settings.yml file.
def cloudwatch_enabled?(options)
!options[:cloudwatch].nil? ?
options[:cloudwatch] : # options can use symbols because this the options hash from Thor
settings["cloudwatch"] # settings uses strings as keys
end
def root
path = ENV['FORGER_ROOT'] || '.'
Pathname.new(path)
end
def validate_in_project!
unless File.exist?("#{root}/profiles")
puts "Could not find a profiles folder in the current directory. It does not look like you are running this command within a forger project. Please confirm that you are in a forger project and try again.".color(:red)
exit
end
end
@@env = nil
def env
return @@env if @@env
env = env_from_profile(ENV['AWS_PROFILE']) || 'development'
env = ENV['FORGER_ENV'] if ENV['FORGER_ENV'] # highest precedence
@@env = env
end
def build_root
Base::BUILD_ROOT
end
# Overrides AWS_PROFILE based on the Forger.env if set in config/settings.yml
# 2-way binding.
def set_aws_profile!
return if ENV['TEST']
return unless File.exist?("#{Forger.root}/config/settings.yml") # for rake docs
return unless settings # Only load if within Ufo project and there's a settings.yml
data = settings[Forger.env] || {}
if data["aws_profile"]
puts "Using AWS_PROFILE=#{data["aws_profile"]} from FORGER_ENV=#{Forger.env} in config/settings.yml"
ENV['AWS_PROFILE'] = data["aws_profile"]
end
end
# Do not use the Setting#data to load the profile because it can cause an
# infinite loop then if we decide to use Forger.env from within settings class.
def settings
path = "#{Forger.root}/config/settings.yml"
return {} unless File.exist?(path)
YAML.load_file(path)
end
memoize :settings
private
# Do not use the Setting class to load the profile because it can cause an
# infinite loop then if we decide to use Forger.env from within settings class.
def env_from_profile(aws_profile)
return unless settings
env = settings.find do |_env, settings|
settings ||= {}
profiles = settings['aws_profile']
profiles && profiles == aws_profile
end
env.first if env
end
end
end
|
tongueroo/forger
|
forger.gemspec
|
# coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "forger/version"
Gem::Specification.new do |spec|
spec.name = "forger"
spec.version = Forger::VERSION
spec.author = "<NAME>"
spec.email = "<EMAIL>"
spec.summary = "Create EC2 Instances with preconfigured settings"
spec.homepage = "https://github.com/tongueroo/forger"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "activesupport"
spec.add_dependency "aws-sdk-cloudformation"
spec.add_dependency "aws-sdk-ec2"
spec.add_dependency "aws-sdk-s3"
spec.add_dependency "cfn-status"
spec.add_dependency "dotenv"
spec.add_dependency "filesize"
spec.add_dependency "hashie"
spec.add_dependency "memoist"
spec.add_dependency "rainbow"
spec.add_dependency "render_me_pretty"
spec.add_dependency "thor"
spec.add_dependency "zeitwerk"
spec.add_development_dependency "bundler"
spec.add_development_dependency "byebug"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-bundler"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "rake"
end
|
tongueroo/forger
|
lib/forger/base.rb
|
module Forger
class Base
# constants really only used by script classes
BUILD_ROOT = "/tmp/forger/#{File.basename(Dir.pwd)}"
SCRIPTS_INFO_PATH = "#{BUILD_ROOT}/data/scripts_info.txt"
def initialize(options={})
@options = options.clone
@name = randomize(@options[:name])
Forger.validate_in_project!
end
# Appends a short random string at the end of the ec2 instance name.
# Later we will strip this same random string from the name.
# Very makes it convenient. We can just type:
#
# forger create server --randomize
#
# instead of:
#
# forger create server-123 --profile server
#
def randomize(name)
if @options[:randomize]
random = (0...3).map { (65 + rand(26)).chr }.join.downcase # Ex: jhx
[name, random].join('-')
else
name
end
end
# Strip the random string at end of the ec2 instance name
def derandomize(name)
if @options[:randomize]
name.sub(/-(\w{3})$/,'') # strip the random part at the end
else
name
end
end
end
end
|
tongueroo/forger
|
lib/forger/create.rb
|
require 'yaml'
require 'active_support/core_ext/hash'
module Forger
class Create < Base
include AwsServices
include ErrorMessages
def run
Profile.new(@options).check!
Hook.run(:before_run_instances, @options)
sync_scripts_to_s3
puts "Creating EC2 instance #{@name.color(:green)}"
info = Info.new(@options, params)
info.ec2_params
if @options[:noop]
puts "NOOP mode enabled. EC2 instance not created."
return
end
resp = run_instances(params)
instance_id = resp.instances.first.instance_id
info.spot(instance_id)
puts "EC2 instance with profile #{@name.color(:green)} created: #{instance_id} 🎉"
puts "Visit https://console.aws.amazon.com/ec2/home to check on the status"
info.cloudwatch(instance_id)
Waiter.new(@options.merge(instance_id: instance_id)).wait
end
def run_instances(params)
ec2.run_instances(params)
rescue Aws::EC2::Errors::ServiceError => e
handle_ec2_service_error!(e)
end
def sync_scripts_to_s3
upload = Script::Upload.new(@options)
upload.run
end
# params are main derived from profile files
def params
@params ||= Params.new(@options).generate
end
end
end
|
tongueroo/forger
|
lib/forger/cleaner.rb
|
<gh_stars>1-10
module Forger
module Cleaner
end
end
|
tongueroo/forger
|
lib/forger/template/helper/script_helper.rb
|
<reponame>tongueroo/forger
module Forger::Template::Helper::ScriptHelper
# Bash code that is meant to included in user-data
def extract_scripts(options={})
settings_options = settings["extract_scripts"] || {}
options = settings_options.merge(options)
# defaults also here in case they are removed from settings
to = options[:to] || "/opt"
user = options[:as] || "ec2-user"
if Dir.glob("#{Forger.root}/app/scripts*").empty?
puts "WARN: you are using the extract_scripts helper method but you do not have any app/scripts.".color(:yellow)
calling_line = caller[0].split(':')[0..1].join(':')
puts "Called from: #{calling_line}"
return ""
end
<<-BASH_CODE
# Generated from the forger extract_scripts helper.
# Downloads scripts from s3, extract them, and setup.
mkdir -p #{to}
aws s3 cp #{scripts_s3_path} #{to}/
(
cd #{to}
rm -rf #{to}/scripts # cleanup
tar zxf #{to}/#{scripts_name}
chmod -R a+x #{to}/scripts
chown -R #{user}:#{user} #{to}/scripts
)
BASH_CODE
end
private
def register_extract_scripts
end
def scripts_name
File.basename(scripts_s3_path)
end
def scripts_s3_path
upload = Forger::Script::Upload.new
upload.s3_dest
end
end
|
tongueroo/forger
|
docs/example/config/variables/development.rb
|
@subnets = %w[subnet-111 subnet-222 subnet-333]
@security_group_ids = %w[sg-111]
|
tongueroo/forger
|
lib/forger/create/info.rb
|
<filename>lib/forger/create/info.rb
class Forger::Create
class Info
include Forger::AwsServices
attr_reader :params
def initialize(options, params)
@options = options
@params = params
end
def ec2_params
puts "Using the following parameters:"
pretty_display(params)
launch_template
end
def spot(instance_id)
retries = 0
begin
resp = ec2.describe_instances(instance_ids: [instance_id])
rescue Aws::EC2::Errors::InvalidInstanceIDNotFound
retries += 1
puts "Aws::EC2::Errors::InvalidInstanceIDNotFound error. Retry: #{retries}"
sleep 2**retries
if retries <= 3
retry
else
puts "Unable to find lauched spot instance"
return
end
end
reservation = resp.reservations.first
# Super edge case when reserverations not immediately found yet
until reservation
resp = ec2.describe_instances(instance_ids: [instance_id])
reservation = resp.reservations.first
seconds = 0.5
puts "Reserveration not found. Sleeping for #{seconds} and will try again."
sleep seconds
end
spot_id = reservation.instances.first.spot_instance_request_id
return unless spot_id
puts "Spot instance request id: #{spot_id}"
end
def launch_template
launch_template = params[:launch_template]
return unless launch_template
resp = ec2.describe_launch_template_versions(
launch_template_id: launch_template[:launch_template_id],
launch_template_name: launch_template[:launch_template_name],
)
versions = resp.launch_template_versions
launch_template_data = {} # combined launch_template_data
versions.sort_by { |v| v[:version_number] }.each do |v|
launch_template_data.merge!(v[:launch_template_data])
end
puts "launch template data (versions combined):"
pretty_display(launch_template_data)
rescue Aws::EC2::Errors::InvalidLaunchTemplateNameNotFoundException => e
puts "ERROR: The specified launched template #{launch_template.inspect} was not found."
puts "Please double check that it exists."
exit
end
def cloudwatch(instance_id)
return unless Forger.cloudwatch_enabled?(@options)
region = cloudwatch_log_region
stream = "#{instance_id}/var/log/cloud-init-output.log"
url = "https://#{region}.console.aws.amazon.com/cloudwatch/home?region=#{region}#logEventViewer:group=forger;stream=#{stream}"
cw_init_log = "cw tail -f forger #{stream}"
puts "To view instance's cloudwatch logs visit:"
puts " #{url}"
puts " #{cw_init_log}" if show_cw
if show_cw && @options[:auto_terminate]
cw_terminate_log = "cw tail -f forger #{instance_id}/var/log/auto-terminate.log"
puts " #{cw_terminate_log}"
end
puts "Note: It takes at least a few minutes for the instance to launch and report logs."
paste_command = show_cw ? cw_init_log : url
add_to_clipboard(paste_command)
end
def cloudwatch_log_region
# Highest precedence: FORGER_REGION env variable. Only really used here.
# This is useful to be able to override when running tool in codebuild.
# Codebuild can be running in different region then the region which the
# instance is launched in.
# Getting the region from the the profile and metadata doesnt work in
# this case.
if ENV['FORGER_REGION']
return ENV['FORGER_REGION']
end
# Pretty high in precedence: AWS_PROFILE and ~/.aws/config and
aws_found = system("type aws > /dev/null")
if aws_found
region = `aws configure get region`.strip
return region
end
# Assumes instance same region as the calling ec2 instance.
# It is possible for curl not to be installed.
curl_found = system("type curl > /dev/null")
if curl_found
region = `curl --connect-timeout 3 -s 169.254.169.254/latest/meta-data/placement/availability-zone | sed s'/.$//'`
return region unless region == ''
end
return 'us-east-1' # fallback default
end
def pretty_display(data)
data = data.deep_stringify_keys
if data["user_data"]
message = "base64-encoded: cat #{Forger.build_root}/user-data.txt to view"
data["user_data"] = message
end
puts YAML.dump(data)
end
def show_cw
ENV['FORGER_CW'] || system("type cw > /dev/null 2>&1")
end
def add_to_clipboard(text)
return unless RUBY_PLATFORM =~ /darwin/
return unless system("type pbcopy > /dev/null")
system(%[echo "#{text}" | pbcopy])
copy_item = show_cw ? "cw command" : "CloudWatch Console Link"
puts "Pro tip: The #{copy_item} has been added to your copy-and-paste clipboard."
end
end
end
|
tongueroo/forger
|
lib/forger/setting.rb
|
require 'yaml'
module Forger
class Setting
def initialize(check_project=true)
@check_project = check_project
end
# data contains the settings.yml config. The order or precedence for settings
# is the project lono/settings.yml and then the ~/.lono/settings.yml.
@@data = nil
def data
return @@data if @@data
if @check_project && !File.exist?(project_settings_path)
puts "ERROR: No settings file at #{project_settings_path}. Are you sure you are in a forger project?".color(:red)
exit 1
end
all_envs = load_file(project_settings_path)
all_envs = merge_base(all_envs)
@@data = all_envs[Forger.env] || all_envs["base"] || {}
@@data
end
private
def load_file(path)
return Hash.new({}) unless File.exist?(path)
content = RenderMePretty.result(path)
data = YAML.load(content)
# If key is is accidentally set to nil it screws up the merge_base later.
# So ensure that all keys with nil value are set to {}
data.each do |env, _setting|
data[env] ||= {}
end
data
end
# automatically add base settings to the rest of the environments
def merge_base(all_envs)
base = all_envs["base"] || {}
all_envs.each do |env, settings|
all_envs[env] = base.merge(settings) unless env == "base"
end
all_envs
end
def project_settings_path
"#{Forger.root}/config/settings.yml"
end
end
end
|
tongueroo/forger
|
spec/spec_helper.rb
|
<reponame>tongueroo/forger<gh_stars>1-10
ENV["TEST"] = "1"
ENV["FORGER_ENV"] = "test"
ENV["FORGER_ROOT"] = "spec/fixtures/demo_project"
# Ensures aws api never called. Fixture home folder does not contain ~/.aws/credentails
ENV['HOME'] = "spec/fixtures/home"
require "pp"
require "byebug"
root = File.expand_path("../", File.dirname(__FILE__))
require "#{root}/lib/forger"
module Helper
def execute(cmd)
puts "Running: #{cmd}" if show_command?
out = `#{cmd}`
puts out if show_command?
out
end
# Added SHOW_COMMAND because DEBUG is also used by other libraries like
# bundler and it shows its internal debugging logging also.
def show_command?
ENV['DEBUG'] || ENV['SHOW_COMMAND']
end
end
RSpec.configure do |c|
c.include Helper
end
|
tongueroo/forger
|
lib/forger/wait.rb
|
module Forger
class Wait < Command
desc "ami", "Wait until AMI available."
long_desc Help.text("wait:ami")
option :timeout, type: :numeric, default: 1800, desc: "Timeout in seconds."
def ami(name)
Waiter::Ami.new(options.merge(name: name)).wait
end
end
end
|
tongueroo/forger
|
lib/forger/s3/bucket.rb
|
require "cfn_status"
class Forger::S3
class Bucket
STACK_NAME = ENV['FORGER_STACK_NAME'] || "forger"
include Forger::AwsServices
extend Forger::AwsServices
class << self
@@name = nil
def name
return @@name if @@name # only memoize once bucket has been created
stack = new.find_stack
return unless stack
resp = cfn.describe_stack_resources(stack_name: STACK_NAME)
bucket = resp.stack_resources.find { |r| r.logical_resource_id == "Bucket" }
@@name = bucket.physical_resource_id # actual bucket name
end
def ensure_exists!
bucket = new
return if bucket.exist?
bucket.create
end
end
def initialize(options={})
@options = options
end
def deploy
stack = find_stack
if stack
update
else
create
end
end
def exist?
!!bucket_name
end
def bucket_name
self.class.name
end
def show
if bucket_name
puts "Forger bucket name: #{bucket_name}"
else
puts "Forger bucket does not exist yet."
end
end
# Launches a cloudformation to create an s3 bucket
def create
puts "Creating #{STACK_NAME} stack with the s3 bucket"
cfn.create_stack(stack_name: STACK_NAME, template_body: template_body)
status = CfnStatus.new(STACK_NAME)
status.wait
end
def update
puts "Updating #{STACK_NAME} stack with the s3 bucket"
cfn.update_stack(stack_name: STACK_NAME, template_body: template_body)
rescue Aws::CloudFormation::Errors::ValidationError => e
raise unless e.message.include?("No updates are to be performed")
end
def delete
are_you_sure?
puts "Deleting #{STACK_NAME} stack with the s3 bucket"
empty_bucket!
cfn.delete_stack(stack_name: STACK_NAME)
end
def find_stack
resp = cfn.describe_stacks(stack_name: STACK_NAME)
resp.stacks.first
rescue Aws::CloudFormation::Errors::ValidationError
nil
end
private
def empty_bucket!
resp = s3.list_objects(bucket: bucket_name)
if resp.contents.size > 0
# IE: objects = [{key: "objectkey1"}, {key: "objectkey2"}]
objects = resp.contents.map { |item| {key: item.key} }
s3.delete_objects(
bucket: bucket_name,
delete: {
objects: objects,
quiet: false,
}
)
empty_bucket! # keep deleting objects until bucket is empty
end
end
def are_you_sure?
return true if @options[:sure]
puts "Are you sure you want the forger bucket #{bucket_name.color(:green)} to be emptied and deleted? (y/N)"
sure = $stdin.gets.strip
yes = sure =~ /^Y/i
unless yes
puts "Phew that was close."
exit
end
end
def template_body
<<~YAML
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
Tags:
- Key: Name
Value: forger
YAML
end
end
end
|
tongueroo/forger
|
lib/forger/template/helper/ssh_key_helper.rb
|
module Forger::Template::Helper::SshKeyHelper
def add_ssh_key(user="ec2-user")
key_path = "#{ENV['HOME']}/.ssh/id_rsa.pub"
if File.exist?(key_path)
public_key = IO.read(key_path).strip
end
if public_key
<<-SCRIPT
# Automatically add user's public key from #{key_path}
cp /home/#{user}/.ssh/authorized_keys{,.bak}
echo #{public_key} >> /home/#{user}/.ssh/authorized_keys
chown #{user}:#{user} /home/#{user}/.ssh/authorized_keys
SCRIPT
else
<<-SCRIPT
# WARN: unable to find a ~/.ssh/id_rsa.pub locally on your machine. user: #{ENV['USER']}
# Unable to automatically add the public key
SCRIPT
end
end
end
|
tongueroo/forger
|
lib/forger/create/waiter.rb
|
class Forger::Create
class Waiter < Forger::Base
include Forger::AwsServices
def wait
@instance_id = @options[:instance_id]
handle_wait if wait?
handle_ssh if @options[:ssh]
end
def handle_wait
puts "Waiting for instance #{@instance_id} to be ready."
# https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/using-waiters.html
ec2.wait_until(:instance_running, instance_ids:[@instance_id]) do |w|
w.interval = 5
w.before_wait do |n, resp|
print '.'
end
end
puts "" # newline
resp = ec2.describe_instances(instance_ids:[@instance_id])
i = resp.reservations.first.instances.first
puts "Instance #{@instance_id} is ready"
dns = i.public_dns_name ? i.public_dns_name : 'nil'
puts "Instance public dns name: #{dns}"
if i.public_dns_name && !@options[:ssh]
command = build_ssh_command(i.public_dns_name)
puts "Ssh command below. Note the user might be different. You can specify --ssh-user=USER. You can also ssh automatically into the instance with the --ssh flag."
display_ssh(command)
end
i
end
def handle_ssh
instance = handle_wait
unless instance.public_dns_name
puts "This instance does not have a public dns for ssh."
return
end
command = build_ssh_command(instance.public_dns_name)
display_ssh(command)
retry_until_success(command)
Kernel.exec(*command) unless @options[:noop]
end
def wait?
return false if @options[:ssh]
@options[:wait]
end
def build_ssh_command(host)
user = @options[:ssh_user] || "ec2-user"
[
"ssh",
ENV['SSH_OPTIONS'],
"#{user}@#{host}"
].compact
end
def display_ssh(command)
puts "=> #{command.join(' ')}".color(:green)
end
def retry_until_success(*command)
retries = 0
uptime = command + ['uptime', '2>&1']
uptime = uptime.join(' ')
out = `#{uptime}`
while out !~ /load average/ do
puts "Can't ssh into the server yet. Retrying until success. (Timeout 10m)" if retries == 0
print '.'
retries += 1
if retries > 600 # Timeout after 10 minutes
raise "ERROR: Timeout after 600 seconds, cannot connect to the server."
end
sleep 1
out = `#{uptime}`
end
puts ""
end
end
end
|
tongueroo/forger
|
lib/forger/script.rb
|
module Forger
class Script
def initialize(options={})
@options = options
end
def add_to_user_data!(user_data)
user_data
end
def auto_terminate_after_timeout
load_template("auto_terminate_after_timeout.sh")
end
def auto_terminate
# set variables for the template
@ami_name = @options[:ami_name]
load_template("auto_terminate.sh")
end
def cloudwatch
load_template("cloudwatch.sh")
end
def create_ami
# set variables for the template
@ami_name = @options[:ami_name]
@region = 'us-east-1' if ENV['TEST']
@region ||= `aws configure get region`.strip rescue 'us-east-1'
load_template("ami_creation.sh")
end
def extract_forger_scripts
load_template("extract_forger_scripts.sh")
end
private
def load_template(name)
template = IO.read(File.expand_path("script/templates/#{name}", File.dirname(__FILE__)))
ERB.new(template, nil, "-").result(binding) # text
end
end
end
|
tongueroo/forger
|
lib/forger/waiter.rb
|
<gh_stars>1-10
module Forger
module Waiter
end
end
|
tongueroo/forger
|
lib/forger/script/upload.rb
|
<reponame>tongueroo/forger<gh_stars>1-10
require 'filesize'
require 'aws-sdk-s3'
require 'fileutils'
require 'memoist'
# Class for forger upload command
class Forger::Script
class Upload < Forger::Base
extend Memoist
def initialize(options={})
@options = options
@compile = @options[:compile] ? @options[:compile] : true
end
def run
return if empty?
ensure_bucket_exists
compiler.compile_scripts if @compile
compressor.compress
upload(tarball_path)
compressor.clean
compiler.clean if @compile and Forger.settings["compile_clean"]
end
def ensure_bucket_exists
Forger::S3::Bucket.ensure_exists!
end
def upload(tarball_path)
if @options[:noop]
puts "NOOP: Not uploading file to s3"
return
end
puts "Uploading scripts.tgz (#{filesize}) to #{s3_dest}".color(:green)
obj = s3_resource.bucket(bucket_name).object(s3_key)
start_time = Time.now
obj.upload_file(tarball_path)
time_took = pretty_time(Time.now-start_time).color(:green)
puts "Time to upload code to s3: #{time_took}"
end
def empty?
Dir.glob("#{Forger.root}/app/scripts/**/*").select do |path|
File.file?(path)
end.empty?
end
def tarball_path
IO.read(SCRIPTS_INFO_PATH).strip
end
def filesize
Filesize.from(File.size(tarball_path).to_s + " B").pretty
end
def s3_dest
"s3://#{bucket_name}/#{s3_key}"
end
def s3_key
# Example s3_key: ec2/development/scripts/scripts-md5
dest_folder = "#{Forger.env}/scripts"
"#{dest_folder}/#{File.basename(tarball_path)}"
end
def bucket_name
Forger::S3::Bucket.name
end
def s3_resource
options = {}
# allow override of region for s3 client to avoid warning:
# S3 client configured for "us-east-1" but the bucket "xxx" is in "us-west-2"; Please configure the proper region to avoid multiple unnecessary redirects and signing attempts
# Example: endpoint: 'https://s3.us-west-2.amazonaws.com'
options[:endpoint] = ENV['FORGER_S3_ENDPOINT'] if ENV['FORGER_S3_ENDPOINT']
if options[:endpoint]
options[:region] = options[:endpoint].split('.')[1]
end
Aws::S3::Resource.new(options)
end
memoize :s3_resource
# http://stackoverflow.com/questions/4175733/convert-duration-to-hoursminutesseconds-or-similar-in-rails-3-or-ruby
def pretty_time(total_seconds)
minutes = (total_seconds / 60) % 60
seconds = total_seconds % 60
if total_seconds < 60
"#{seconds.to_i}s"
else
"#{minutes.to_i}m #{seconds.to_i}s"
end
end
def sh(command)
puts "=> #{command}"
system command
end
def compiler
@compiler ||= Compile.new(@options)
end
def compressor
@compressor ||= Compress.new(@options)
end
end
end
|
tongueroo/forger
|
spec/lib/core_helper_spec.rb
|
describe Forger::Template::Helper::CoreHelper do
let(:thing) do
thing = Class.new
Forger::Template::Helper::CoreHelper.send :public, :normalize_user_data_name_input
thing.extend(Forger::Template::Helper::CoreHelper)
thing
end
it 'normalize user_data name input' do
result = thing.normalize_user_data_name_input("ecs.sh")
expect(result).to eq "ecs.sh"
result = thing.normalize_user_data_name_input("ecs")
expect(result).to eq "ecs.sh"
result = thing.normalize_user_data_name_input("test/ecs")
expect(result).to eq "test/ecs.sh"
end
end
|
tongueroo/forger
|
lib/forger/template/helper.rb
|
require "active_support/core_ext/string"
module Forger::Template
module Helper
include AmiHelper
include CoreHelper
include PartialHelper
include ScriptHelper
include SshKeyHelper
extend self
end
end
|
tongueroo/forger
|
lib/forger/template/context.rb
|
<reponame>tongueroo/forger
require "active_support/core_ext/string"
# Encapsulates helper methods and instance variables to be rendered in the ERB
# templates.
module Forger::Template
class Context
include Forger::Template::Helper
def initialize(options={})
@options = options
load_variables
load_custom_helpers
end
private
# Load variables from:
# config/variables/development.rb
# config/variables/production.rb
# etc
def load_variables
load_variables_file(:base)
load_variables_file(Forger.env)
end
def load_variables_file(type)
path = "#{Forger.root}/config/variables/#{type}.rb"
instance_eval(IO.read(path), path) if File.exist?(path)
end
# Load custom helper methods from project
def load_custom_helpers
Dir.glob("#{Forger.root}/app/helpers/**/*_helper.rb").each do |path|
filename = path.sub(%r{.*/},'').sub('.rb','')
module_name = filename.camelize
# Prepend a period so require works FORGER_ROOT is set to a relative path
# without a period.
#
# Example: FORGER_ROOT=tmp/project
first_char = path[0..0]
path = "./#{path}" unless %w[. /].include?(first_char)
require path
self.class.send :include, module_name.constantize
end
end
end
end
|
tongueroo/forger
|
lib/forger/hook.rb
|
require 'yaml'
module Forger
class Hook
def initialize(options={})
@options = options
end
def run(name)
return if @options[:noop]
return unless hooks[name]
command = hooks[name]
puts "Running hook #{name}: #{command}"
sh(command)
end
def hooks
hooks_path = "#{Forger.root}/config/hooks.yml"
data = File.exist?(hooks_path) ? YAML.load_file(hooks_path) : {}
data ? data : {} # in case the file is empty
end
def sh(command)
puts "=> #{command}".color(:green)
success = system(command)
abort("Command failed") unless success
end
def self.run(name, options={})
Hook.new(options).run(name.to_s)
end
end
end
|
tongueroo/forger
|
lib/forger/new.rb
|
<gh_stars>1-10
module Forger
class New < Sequence
argument :project_name
# Ugly, but when the class_option is only defined in the Thor::Group class
# it doesnt show up with cli-template new help :(
# If anyone knows how to fix this let me know.
# Also options from the cli can be pass through to here
def self.cli_options
[
[:force, type: :boolean, desc: "Bypass overwrite are you sure prompt for existing files."],
[:git, type: :boolean, default: true, desc: "Git initialize the project"],
[:iam, desc: "iam_instance_profile to use in the profiles/default.yml"],
[:key_name, desc: "key name to use with launched instance in profiles/default.yml"],
[:security_group, desc: "Security group to use. For config/variables/development.rb network settings."],
[:subnet, desc: "Subnet to use. For config/variables/development.rb network settings."],
[:vpc_id, desc: "Vpc id. For config/variables/development.rb network settings. Will use default sg and subnet"],
]
end
cli_options.each do |args|
class_option(*args)
end
def configure_network_settings
return if ENV['TEST']
network = Network.new(@options[:vpc_id]) # used for default settings
@subnet = @options[:subnet] || network.subnet_ids.first
@security_group = @options[:security_group] || network.security_group_id
end
def create_project
copy_project
destination_root = "#{Dir.pwd}/#{project_name}"
self.destination_root = destination_root
FileUtils.cd("#{Dir.pwd}/#{project_name}")
end
def make_executable
chmod("exe", 0755 & ~File.umask, verbose: false) if File.exist?("exe")
end
def bundle_install
Bundler.with_clean_env do
system("BUNDLE_IGNORE_CONFIG=1 bundle install")
end
end
def git_init
return if !options[:git]
return unless git_installed?
return if File.exist?(".git") # this is a clone repo
run("git init")
run("git add .")
run("git commit -m 'first commit'")
end
def user_message
puts <<-EOL
#{"="*64}
Congrats 🎉 You have successfully generated a starter forger project.
Test the CLI:
cd #{project_name}
forger create box --noop # dry-run to see the tmp/user-data.txt script
forger create box # live-run
forger create box --ssh
EOL
end
end
end
|
tongueroo/forger
|
lib/forger/ami.rb
|
module Forger
class Ami < Base
def run
# Delegates to the Create command.
# So we just have to set up the option for it.
@options[:ami_name] = @name
Create.new(@options).run
end
end
end
|
tongueroo/forger
|
lib/forger/destroy.rb
|
<reponame>tongueroo/forger
module Forger
class Destroy < Base
include AwsServices
def run(instance_id)
puts "Destroying #{instance_id}"
return if ENV['TEST']
cancel_spot_request(instance_id)
ec2.terminate_instances(instance_ids: [instance_id])
puts "Instance #{instance_id} terminated."
end
def cancel_spot_request(instance_id)
resp = ec2.describe_instances(instance_ids: [instance_id])
spot_id = resp.reservations.first.instances.first.spot_instance_request_id
return unless spot_id
ec2.cancel_spot_instance_requests(spot_instance_request_ids: [spot_id])
puts "Spot instance request #{spot_id} cancelled."
end
end
end
|
tongueroo/forger
|
spec/lib/cli_spec.rb
|
<reponame>tongueroo/forger
describe Forger::CLI do
before(:all) do
@args = "--noop"
end
describe "forger" do
it "create" do
out = execute("exe/forger create server #{@args}")
expect(out).to include("Creating EC2 instance")
end
it "ERB evaluates dotenv files" do
out = execute("exe/forger create server #{@args}")
project_name = ENV['CIRCLECI'] ? 'repo' : 'forger'
user_data = IO.readlines("/tmp/forger/#{project_name}/user-data.txt")
found = !user_data.select { |l| l =~ /test_key: test-key-value/ }.empty?
expect(found).to be true
end
it "ami" do
out = execute("exe/forger ami myimage #{@args}")
expect(out).to include("Creating EC2 instance")
end
it "wait ami" do
out = execute("exe/forger wait ami myimage")
expect(out).to include("Waiting for")
end
it "clean ami" do
out = execute("exe/forger clean ami imagebasename")
expect(out).to include("Cleaning out old AMIs")
end
it "destroy" do
out = execute("exe/forger destroy i-123")
expect(out).to include("Destroying i-123")
end
commands = {
"am" => "ami",
"compile" => "--profile",
"create -" => "--profile",
"create" => "name",
"create name --" => "--profile",
}
commands.each do |command, expected_word|
it "completion #{command}" do
out = execute("exe/forger completion #{command}")
expect(out).to include(expected_word) # only checking for one word for simplicity
end
end
end
end
|
tongueroo/forger
|
lib/forger/waiter/ami.rb
|
module Forger::Waiter
class Ami < Forger::Base
include Forger::AwsServices
def wait
delay = 30
timeout = @options[:timeout]
max_attempts = timeout / delay
current_time = 0
puts "Waiting for #{@options[:name]} to be available. Delay: #{delay}s. Timeout: #{timeout}s"
puts "Current time: #{Time.now}"
return if ENV['TEST']
# Using while loop because of issues with ruby's Timeout module
# http://www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/
detected = detect_ami
until detected || current_time > timeout
print '.'
sleep delay
current_time += 30
detected = detect_ami
end
puts
if current_time > timeout
puts "ERROR: Timeout. Unable to detect and available ami: #{@options[:name]}"
exit 1
else
puts "Found available AMI: #{@options[:name]}"
end
end
private
# Using custom detect_ami instead of ec2.wait_until(:image_availalbe, ...)
# because we start checking for the ami even before we've called
# create_ami. We start checking right after we launch the instance
# which will create the ami at the end.
def detect_ami(owners=["self"])
images = ec2.describe_images(
owners: owners,
filters: filters
).images
detected = images.first
!!detected
end
def filters
name_is_ami_id = @options[:name] =~ /^ami-/
filters = [{name: "state", values: ["available"]}]
filters << if name_is_ami_id
{name: "image-id", values: [@options[:name]]}
else
{name: "name", values: [@options[:name]]}
end
filters
end
end
end
|
tongueroo/forger
|
lib/forger/template/helper/ami_helper.rb
|
<reponame>tongueroo/forger
module Forger::Template::Helper::AmiHelper
include Forger::AwsServices
# Example:
#
# latest_ami("ruby-2.5.0_*") => ami-122
#
# Equivalent aws cli test command:
#
# $ aws ec2 describe-images --owners self --filters="Name=name,Values=ruby-2.5.0_*" | jq '.Images | length'
#
# Returns latest ami ami
def latest_ami(query, owners=["self"])
images = search_ami(query, owners)
image = images.sort_by(&:name).reverse.first
if image
image.image_id
else
puts "latest_ami helper method could not find an AMI with the query of: #{query.inspect}".color(:red)
exit 1
end
end
def search_ami(query, owners=["self"])
ec2.describe_images(
owners: owners,
filters: [
{name: "name", values: [query]},
{name: "state", values: ["available"]}
]
).images
end
end
|
tongueroo/forger
|
lib/forger/template/helper/core_helper.rb
|
<reponame>tongueroo/forger<gh_stars>1-10
require "base64"
require "erb"
module Forger::Template::Helper::CoreHelper
# assuming user-data script is a bash script for simplicity for now
def user_data(name, base64:true, layout:"default")
name = normalize_user_data_name_input(name)
layout_path = layout_path(layout)
path = "#{Forger.root}/app/user_data/#{name}"
unless File.exist?(path)
puts "ERROR: user-data script #{path.color(:red)} does not exist"
exit 1
end
result = RenderMePretty.result(path, context: self, layout: layout_path)
# Must prepend and append scripts in user_data here because we need to
# encode the user_data script for valid yaml to load in the profile.
# Tried moving this logic to the params but that is too late and produces
# invalid yaml. Unless we want to encode and dedode twice.
scripts = [result]
scripts = prepend_scripts(scripts)
scripts = append_scripts(scripts)
divider = "\n############################## DIVIDER ##############################\n"
result = scripts.join(divider)
# save the unencoded user-data script for easy debugging
temp_path = "#{Forger.build_root}/user-data.txt"
FileUtils.mkdir_p(File.dirname(temp_path))
IO.write(temp_path, result)
base64 ? Base64.encode64(result).strip : result
end
# Get full path of layout from layout name
#
# layout_name=false - dont use layout at all
# layout_name=nil - default to default.sh layout if available
def layout_path(name="default")
return false if name == false # disable layout
name = "default" if name.nil? # in case user passes in nil
ext = File.extname(name)
name += ".sh" if ext.empty?
layout_path = "#{Forger.root}/app/user_data/layouts/#{name}"
# special rule for default in case there's no default layout
if name.include?("default") and !File.exist?(layout_path)
return false
end
# other named layouts should error if it doesnt exit
unless File.exist?(layout_path)
puts "ERROR: Layout #{layout_path} does not exist. Are you sure it exists? Exiting".color(:red)
exit 1
end
layout_path
end
# provides access to config/* settings as variables
# FORGER_ENV=development => config/variables/development.rb
# FORGER_ENV=production => config/variables/production.rb
def vars
Forger.vars
end
alias_method :variables, :vars
# provides access to config/settings.yml as variables
def settings
Forger.settings
end
# pretty timestamp that is useful for ami ids.
# the timestamp is generated once and cached.
def timestamp
@timestamp ||= Time.now.strftime("%Y-%m-%d-%H-%M-%S")
end
private
def cloudwatch_enabled?
Forger.cloudwatch_enabled?(@options)
end
# TODO: move script combining logic into class
def prepend_scripts(scripts)
scripts.unshift(script.cloudwatch) if cloudwatch_enabled?
scripts.unshift(script.auto_terminate_after_timeout) if @options[:auto_terminate]
add_setup_script(scripts, :prepend)
scripts
end
def append_scripts(scripts)
add_setup_script(scripts, :append)
scripts << script.auto_terminate if @options[:auto_terminate]
scripts << script.create_ami if @options[:ami_name]
scripts
end
def add_setup_script(scripts, how)
return if @already_setup
@already_setup = true
requires_setup = cloudwatch_enabled? ||
@options[:auto_terminate] ||
@options[:ami_name]
return unless requires_setup
if how == :prepend
scripts.unshift(script.extract_forger_scripts)
else
scripts << script.extract_forger_scripts
end
scripts
end
def script
@script ||= Forger::Script.new(@options)
end
# Load custom helper methods from the project repo
def load_custom_helpers
Dir.glob("#{Forger.root}/app/helpers/**/*_helper.rb").each do |path|
filename = path.sub(%r{.*/},'').sub('.rb','')
module_name = filename.camelize
require path
self.class.send :include, module_name.constantize
end
end
private
def normalize_user_data_name_input(name)
ext = File.extname(name)
name += ".sh" if ext.empty?
name
end
end
|
tongueroo/forger
|
lib/templates/default/app/helpers/application_helper.rb
|
module ApplicationHelper
def personalize_script
path = File.expand_path("../../scripts/personalize/#{ENV['USER']}.sh", __FILE__)
if File.exist?(path)
script =<<EOL
#######################################
# personalize script added by ApplicationHelper#personalize_script for #{ENV['USER']}
/opt/scripts/personalize/tung.sh
EOL
end
end
end
|
tongueroo/forger
|
lib/forger/template.rb
|
require "active_support" # for autoload
require "active_support/core_ext/string"
module Forger
module Template
def context
@context ||= Forger::Template::Context.new(@options)
end
end
end
|
tongueroo/forger
|
lib/forger/clean.rb
|
module Forger
class Clean < Command
desc "ami", "Clean until AMI available."
long_desc Help.text("clean:ami")
option :keep, type: :numeric, default: 2, desc: "Number of images to keep"
option :noop, type: :boolean, desc: "Noop or dry-run mode"
def ami(query)
Cleaner::Ami.new(options.merge(query: query)).clean
end
end
end
|
tongueroo/forger
|
lib/forger/dotenv.rb
|
<filename>lib/forger/dotenv.rb
require 'dotenv'
require 'pathname'
class Forger::Dotenv
class << self
def load!
::Dotenv.load(*dotenv_files)
end
# dotenv files will load the following files, starting from the bottom. The first value set (or those already defined in the environment) take precedence:
# - `.env` - The Original®
# - `.env.development`, `.env.test`, `.env.production` - Environment-specific settings.
# - `.env.local` - Local overrides. This file is loaded for all environments _except_ `test`.
# - `.env.development.local`, `.env.test.local`, `.env.production.local` - Local overrides of environment-specific settings.
#
def dotenv_files
[
root.join(".env.#{Forger.env}.local"),
(root.join(".env.local") unless Forger.env == "test"),
root.join(".env.#{Forger.env}"),
root.join(".env")
].compact
end
def root
Forger.root || Pathname.new(ENV["FORGER_ROOT"] || Dir.pwd)
end
end
end
|
tongueroo/forger
|
lib/forger/template/helper/partial_helper.rb
|
<reponame>tongueroo/forger<gh_stars>1-10
module Forger::Template::Helper::PartialHelper
def partial_exist?(path)
path = partial_path_for(path)
path = auto_add_format(path)
path && File.exist?(path)
end
# The partial's path is a relative path given without the extension and
#
# Example:
# Given: file in app/partials/mypartial.sh
# The path should be: mypartial
#
# If the user specifies the extension then use that instead of auto-adding
# the detected format.
def partial(path,vars={}, options={})
path = partial_path_for(path)
path = auto_add_format(path)
result = RenderMePretty.result(path, context: self)
result = indent(result, options[:indent]) if options[:indent]
if options[:indent]
# Add empty line at beginning because empty lines gets stripped during
# processing anyway. This allows the user to call partial without having
# to put the partial call at very beginning of the line.
# This only should happen if user is using indent option.
["\n", result].join("\n")
else
result
end
end
# add indentation
def indent(text, indentation_amount)
text.split("\n").map do |line|
" " * indentation_amount + line
end.join("\n")
end
private
def partial_path_for(path)
"#{Forger.root}/app/partials/#{path}"
end
def auto_add_format(path)
# Return immediately if user provided explicit extension
extension = File.extname(path) # current extension
return path if !extension.empty?
# Else let's auto detect
paths = Dir.glob("#{path}.*")
if paths.size == 1 # non-ambiguous match
return paths.first
end
if paths.size > 1 # ambiguous match
puts "ERROR: Multiple possible partials found:".color(:red)
paths.each do |path|
puts " #{path}"
end
puts "Please specify an extension in the name to remove the ambiguity.".color(:green)
exit 1
end
# Account for case when user wants to include a file with no extension at all
return path if File.exist?(path) && !File.directory?(path)
path # original path if this point is reached
end
end
|
tongueroo/forger
|
lib/forger/s3.rb
|
<filename>lib/forger/s3.rb<gh_stars>1-10
module Forger
class S3 < Command
desc "deploy", "deploys forger managed s3 bucket"
long_desc Help.text("s3/deploy")
def deploy
Bucket.new(options).deploy
end
desc "show", "shows forger managed s3 bucket"
long_desc Help.text("s3/show")
option :sure, type: :boolean, desc: "Bypass are you sure prompt"
def show
Bucket.new(options).show
end
desc "delete", "deletes forger managed s3 bucket"
long_desc Help.text("s3/delete")
option :sure, type: :boolean, desc: "Bypass are you sure prompt"
def delete
Bucket.new(options).delete
end
end
end
|
tongueroo/forger
|
lib/forger/sequence.rb
|
<gh_stars>1-10
require 'fileutils'
require 'active_support/core_ext/string'
require 'thor'
require 'bundler'
class Forger::Sequence < Thor::Group
include Thor::Actions
# include Forger::Helper
def self.source_root
template = ENV['TEMPLATE'] || 'default'
File.expand_path("../../templates/#{template}", __FILE__)
end
private
def copy_project
puts "Creating new forger project called #{project_name}."
directory ".", project_name
end
def git_installed?
system("type git > /dev/null")
end
end
|
tongueroo/forger
|
lib/forger.rb
|
$:.unshift(File.expand_path("../", __FILE__))
require "forger/version"
require "rainbow/ext/string"
require "render_me_pretty"
require "memoist"
require "forger/autoloader"
Forger::Autoloader.setup
module Forger
extend Core
end
Forger::Dotenv.load!
Forger.set_aws_profile!
|
tongueroo/forger
|
spec/lib/params_spec.rb
|
describe Forger::Create::Params do
let(:param) { Forger::Create::Params.new(name: "myserver") }
context "completely empty" do
it '#upsert_name_tag!' do
params = {}
result = param.upsert_name_tag!(params)
# puts "params: #{params.inspect}" # uncomment to see and debug
expect(result).to eq(
{"tag_specifications"=>
[{"resource_type"=>"instance",
"tags"=>[{"key"=>"Name", "value"=>"myserver"}]}]}
)
end
end
context "empty tag_specifications" do
it '#upsert_name_tag!' do
params = {"tag_specifications" => []}
result = param.upsert_name_tag!(params)
# puts "params: #{params.inspect}" # uncomment to see and debug
expect(result).to eq(
{"tag_specifications"=>
[{"resource_type"=>"instance",
"tags"=>[{"key"=>"Name", "value"=>"myserver"}]}]}
)
end
end
context "contains 1 instance with name" do
it '#upsert_name_tag!' do
params = { "tag_specifications" =>
[{
"resource_type"=>"instance",
"tags"=> [{"key"=>"Name", "value"=>"override-myserver"} ]
}]
}
result = param.upsert_name_tag!(params)
# puts "params: #{params.inspect}" # uncomment to see and debug
expect(result).to eq(
{"tag_specifications"=>
[{"resource_type"=>"instance",
"tags"=>[{"key"=>"Name", "value"=>"override-myserver"}]}]}
)
end
end
context "contains 1 instance with non-name tag" do
it '#upsert_name_tag!' do
params = { "tag_specifications" =>
[{
"resource_type"=>"instance",
"tags"=> [{"key"=>"Os", "value"=>"amazonlinux"} ]
}]
}
result = param.upsert_name_tag!(params)
# puts "params: #{params.inspect}" # uncomment to see and debug
expect(result).to eq(
{ "tag_specifications" =>
[{
"resource_type"=>"instance",
"tags"=> [
{"key"=>"Os", "value"=>"amazonlinux"},
{"key"=>"Name", "value"=>"myserver"},
]
}]
}
)
end
end
end
|
clay-siefken/pe1
|
src/PE1.ruby
|
sum = 0
for i in (1..999)
if i % 3 == 0 or i % 5 == 0
sum = sum + i
end
end
print sum
|
iammouaz/Recipe-app
|
app/controllers/foods_controller.rb
|
<reponame>iammouaz/Recipe-app<gh_stars>0
class FoodsController < ApplicationController
before_action :set_food, only: %i[show edit update destroy]
# GET /foods or /foods.json
def index
@foods = Food.includes(:user).where("user_id = #{current_user.id}")
end
# GET /foods/1 or /foods/1.json
def show; end
# GET /foods/new
def new
@food = Food.new
end
# GET /foods/1/edit
def edit; end
# POST /foods or /foods.json
def create
@food = Food.new food_params.merge(user_id: current_user.id)
respond_to do |format|
if @food.save
format.html { redirect_to food_url(@food), notice: 'Food was successfully created.' }
format.json { render :show, status: :created, location: @food }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @food.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /foods/1 or /foods/1.json
def update
respond_to do |format|
if @food.update(food_params)
format.html { redirect_to food_url(@food), notice: 'Food was successfully updated.' }
format.json { render :show, status: :ok, location: @food }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @food.errors, status: :unprocessable_entity }
end
end
end
# DELETE /foods/1 or /foods/1.json
def destroy
@food.destroy
respond_to do |format|
format.html { redirect_to foods_url, notice: 'Food was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_food
@food = Food.find(params[:id])
end
# Only allow a list of trusted parameters through.
def food_params
params.require(:food).permit(:name, :measurement_unit, :price)
end
end
|
iammouaz/Recipe-app
|
config/routes.rb
|
Rails.application.routes.draw do
devise_for :users, :controllers => {:registrations => "registrations"}
resources :recipes
resources :foods
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
root "foods#index"
delete '/foods/:id', to: 'food#destroy', as: "delete_food"
get '/public_recipes', to: 'recipes#public_recipes', as: "public_recipes"
end
|
iammouaz/Recipe-app
|
app/controllers/registrations_controller.rb
|
class RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(_resource)
foods_path
end
end
|
iammouaz/Recipe-app
|
db/seeds.rb
|
<reponame>iammouaz/Recipe-app
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }])
# Character.create(name: "Luke", movie: movies.first)
user = User.create(name: "John", email: "<EMAIL>", password: "<PASSWORD>")
apple = user.foods.create(name: "apple", measurement_unit: "unit", price: 4)
wheat = user.foods.create(name: "wheat", measurement_unit: "gram", price: 0.5)
sugar = user.foods.create(name: "sugar", measurement_unit: "gram", price: 0.2)
user.save
recipe = Recipe.create(name: "apple pie", preparation_time: 30, cooking_time: 40, description: "lorem ipsum", public: true, user_id: 1)
recipe.save
recipe2 = Recipe.create(name: "apple candy", preparation_time: 10, cooking_time: 10, description: "candy", public: false, user_id: 1)
recipe2.save
|
toshimaru/rails-mem-cache-configuration
|
lib/memcacher.rb
|
<reponame>toshimaru/rails-mem-cache-configuration<gh_stars>0
require "memcacher/version"
require "active_support/cache/memcacher"
module Memcacher
# Your code goes here...
end
|
toshimaru/rails-mem-cache-configuration
|
test/memcacher_test.rb
|
<reponame>toshimaru/rails-mem-cache-configuration
require "test_helper"
require "active_support/cache"
require "active_support/testing/method_call_assertions"
class MemcacherTest < Minitest::Test
include ActiveSupport::Testing::MethodCallAssertions
def test_no_memcache_config
error = assert_raises(RuntimeError) do
@cache = ActiveSupport::Cache.lookup_store(:memcacher)
end
assert_equal("Could not load memcache configuration. No such file - config/memcached.yml", error.message)
end
def test_call_dalli_client_with_yaml_given_params
memcache_configure do
assert_called_with(Dalli::Client, :new, [%w[localhost:11211], {}]) do
@cache = ActiveSupport::Cache.lookup_store(:memcacher)
end
end
end
private
def memcache_configure(&block)
put_config_file
block.call
rescue => e
raise e
ensure
remove_config_file
end
def put_config_file
FileUtils.mkdir("config")
FileUtils.cp("test/config/memcached.yml", "config/memcached.yml")
end
def remove_config_file
FileUtils.rm_r("config")
end
end
|
toshimaru/rails-mem-cache-configuration
|
lib/active_support/cache/memcacher.rb
|
<reponame>toshimaru/rails-mem-cache-configuration
require "rails"
module ActiveSupport
module Cache
class Memcacher < MemCacheStore
CONFIG_PATH = "config/memcached.yml"
def initialize
servers = []
config = memcache_configuration[Rails.env]
# TODO: if config is array
servers << "#{config["host"]}:#{config["port"]}"
super(servers)
end
private
def memcache_configuration
yaml = Pathname.new(CONFIG_PATH)
if yaml.exist?
YAML.load(yaml.read)
else
raise "Could not load memcache configuration. No such file - #{CONFIG_PATH}"
end
end
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot/product.rb
|
require "aliyun_iot/request/json"
module AliyunIot
include ERB::Util
class Product
attr_reader :key
delegate :to_s, to: :key
class << self
def [](key)
Product.new(key)
end
def create(name)
params = { Name: name }
execute params, 'CreateProduct'
end
def check_regist_state(apply_id)
params = { ApplyId: apply_id }
execute params, 'QueryApplyStatus'
end
def list_regist_info(apply_id, page_size, current_page)
params = { ApplyId: apply_id, PageSize: page_size, CurrentPage: current_page }
execute params, 'QueryPageByApplyId'
end
def execute(params = {}, actiont)
Request::Json.post(params.merge({ Action: actiont }))
end
end
def initialize(key)
@key = key
end
def update(params = {})
execute params, 'UpdateProduct'
end
def list(params = {})
execute params, 'QueryDevice'
end
def regist_device(params = {})
execute params, 'RegistDevice'
end
def regist_devices(params = {})
execute params, 'ApplyDeviceWithNames'
end
def batch_get_device_state(params = {})
execute params, 'BatchGetDeviceState'
end
def pub(params = {})
raise RequestException.new(Exception.new("message MessageContent is empty!")) if params[:MessageContent].nil?
params[:MessageContent] = Base64.encode64(params[:MessageContent]).chomp
execute params, 'Pub'
end
def sub(params = {})
execute params, 'Sub'
end
def rrpc(params = {})
execute params, 'RRpc'
end
private
def execute(res_params, action)
Request::Json.post(res_params.merge({ ProductKey: @key, Action: action }))
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot/result.rb
|
module AliyunIot
class Result
attr_reader :h, :queue
def initialize(queue, content, *path)
@queue = queue
@h = path.blank? ? Hash.xml_object(content, "Message") : Hash.xml_array(content, *path)
end
def get_message
h.is_a?(Array) ? h.map{ |message| Message.new(queue, message) } : Message.new(queue, h)
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot/version.rb
|
<gh_stars>0
module AliyunIot
VERSION = "0.1.4"
end
|
insub/aliyun_iot
|
lib/aliyun_iot/message.rb
|
require "aliyun_iot/request/xml"
module AliyunIot
class Message
attr_reader :h, :queue, :id, :body_md5, :body, :receipt_handle, :enqueue_at, :first_enqueue_at, :next_visible_at, :dequeue_count, :priority
def initialize(queue, h)
@h = h
@queue = queue
set_message_info
end
#删除消息
def delete
check_receipt_handle
data = set_data({ReceiptHandle: receipt_handle})
Request::Xml.delete(queue.messages_path, data)
end
#修改消息可见时间
def change_visibility(seconds)
check_receipt_handle
data = set_data({ReceiptHandle: receipt_handle, VisibilityTimeout: seconds})
Request::Xml.put(queue.messages_path, data)
end
def get_data
data = JSON.parse(Base64.decode64 body)
end
def to_s
s = {
"队列" => queue.name,
"ID" => id,
"MD5" => body_md5,
"Receipt handle" => receipt_handle,
"Enqueue at" => enqueue_at,
"First enqueue at" => first_enqueue_at,
"Next visible at" => next_visible_at,
"Dequeue count" => dequeue_count,
"Priority" => priority
}.collect { |k, v| "#{k}: #{v}" }
sep = "\n=============================================>"
s.unshift sep
s << sep
s << body
puts s.join("\n")
end
private
def set_message_info
@id = h["MessageId"]
@body_md5 = h["MessageBodyMD5"]
@body = h["MessageBody"]
@enqueue_at = Time.at(h["EnqueueTime"].to_i/1000.0)
@first_enqueue_at = Time.at(h["FirstDequeueTime"].to_i/1000.0)
@dequeue_count = h["DequeueCount"].to_i
@priority = h["Priority"].to_i
@receipt_handle = h["ReceiptHandle"]
@next_visible_at = Time.at(h["NextVisibleTime"].to_i/1000.0)
end
def set_data(query)
{mqs_headers: {"x-mns-version" => "2015-06-06"}, query: query}
end
def check_receipt_handle
raise "No receipt handle for this operation" unless receipt_handle
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot/request/xml.rb
|
require 'base64'
require_relative 'http_client'
module AliyunIot
module Request
class RequestException < Exception
attr_reader :content
delegate :[], to: :content
def initialize(ex)
@content = Hash.xml_object(ex.to_s, "Error")
rescue
@content = {"Message" => ex.message}
end
end
class Xml
attr_reader :uri, :method, :body, :content_md5, :content_type, :content_length, :mqs_headers, :client
delegate :access_key_id, :access_key_secret, :end_point, to: :configuration
class << self
[:get, :delete, :put, :post].each do |m|
define_method m do |*args, &block|
options = {method: m, path: args[0], mqs_headers: {}, query: {}}
options.merge!(args[1]) if args[1].is_a?(Hash)
request = Request::Xml.new(options)
block.call(request) if block
request.execute
end
end
end
def initialize(method: "get", path: "/", mqs_headers: {}, query: {})
conf = {
host: end_point,
path: path
}
conf.merge!(query: query.to_query) unless query.empty?
@uri = URI::HTTP.build(conf)
@method = method
@client = HttpClient.new(@uri.to_s)
@mqs_headers = mqs_headers.merge("x-mns-version" => "2015-06-06")
end
def content(type, values={})
ns = "http://mns.aliyuncs.com/doc/v1/"
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.send(type.to_sym, xmlns: ns) do |b|
values.each { |k, v| b.send k.to_sym, v }
end
end
@body = builder.to_xml
@content_md5 = Base64::encode64(Digest::MD5.hexdigest(body)).chop
@content_length = body.size
@content_type = "text/xml;charset=utf-8"
end
def execute
date = DateTime.now.httpdate
headers = {
"Authorization" => authorization(date),
"Content-Length" => content_length || 0,
"Content-Type" => content_type,
"Content-MD5" => content_md5,
"Date" => date,
"Host" => uri.host
}.merge(mqs_headers).reject { |k, v| v.nil? }
client.send *[method, body, headers].compact
end
private
def configuration
AliyunIot.configuration
end
def authorization(date)
canonical_resource = [uri.path, uri.query].compact.join("?")
canonical_mq_headers = mqs_headers.sort.collect { |k, v| "#{k.downcase}:#{v}" }.join("\n")
method = self.method.to_s.upcase
signature = [method, content_md5 || "", content_type || "", date, canonical_mq_headers, canonical_resource].join("\n")
sha1 = OpenSSL::HMAC.digest("sha1", access_key_secret, signature)
"MNS #{access_key_id}:#{Base64.encode64(sha1).chop}"
end
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot/request/http_client.rb
|
<filename>lib/aliyun_iot/request/http_client.rb
module AliyunIot
module Request
class HttpClient
attr_reader :base
def initialize(base)
@base = RestClient::Resource.new base
end
[:get, :delete, :put, :post].each do |m|
define_method m do |*args, &block|
begin
re = base.send *[m, args[0], args[1]].compact
rescue RestClient::NotFound => ex
return nil
rescue RestClient::Exception => ex
logger = Logger.new(STDOUT)
logger.error ex.message
logger.error ex.backtrace.join("\n")
raise ex
end
end
end
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot/request/json.rb
|
<gh_stars>0
require 'base64'
require 'securerandom'
require_relative 'http_client'
module AliyunIot
module Request
class Json
attr_reader :url, :method, :body, :params, :client
delegate :access_key_id, :access_key_secret, :base_url, :region_id, to: :configuration
class << self
[:get, :delete, :put, :post].each do |m|
define_method m do |*args, &block|
options = {method: m, params: args[0]}
request = Request::Json.new(options)
request.execute
end
end
end
def initialize(method: "post", params: {})
@params = params
@method = method
@client = HttpClient.new(base_url)
end
def execute
ts = Time.now.utc.strftime('%FT%TZ')
base_params = {
Format: 'JSON',
Version: params[:ApiVersion] || '2018-01-20', # 2017-04-20 / 2018-01-20
AccessKeyId: access_key_id,
SignatureMethod: 'HMAC-SHA1',
Timestamp: ts,
SignatureVersion: '1.0',
SignatureNonce: SecureRandom.uuid,
RegionId: region_id,
ServiceCode: 'iot',
}
exec_params = encode base_params.merge!(params)
begin
JSON.parse client.send(method, exec_params).body
rescue => e
logger = Logger.new(STDOUT)
logger.error e.message
logger.error e.backtrace.join("\n")
raise e
end
end
private
def configuration
AliyunIot.configuration
end
def encode(encode_params)
str = ERB::Util.url_encode(encode_params.to_param)
string_to_sign = "#{method.upcase}&%2F&#{str}"
sign = Base64.encode64(OpenSSL::HMAC.digest("sha1", "#{access_key_secret}&", string_to_sign)).chop
encode_params.merge({ Signature: sign })
end
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot/topic.rb
|
require "aliyun_iot/request/xml"
module AliyunIot
include ERB::Util
class Topic
attr_reader :name, :subscription_name
delegate :to_s, to: :name
class << self
def [](name, subscription_name = nil)
Topic.new(name, subscription_name)
end
def topics(opts = {})
mqs_options = {query: "x-mns-prefix", offset: "x-mns-marker", size: "x-mns-ret-number"}
mqs_headers = opts.slice(*mqs_options.keys).reduce({}) { |mqs_headers, item| k, v = *item; mqs_headers.merge!(mqs_options[k] => v) }
response = Request::Xml.get("/topics", mqs_headers: mqs_headers)
Hash.xml_array(response, "Topics", "Topic").collect { |item| Topic.new(URI(item["TopicURL"]).path.sub!(/^\/topics\//, "")) }
end
end
def initialize(name, subscription_name = nil)
@name = name
@subscription_name = subscription_name
end
#创建topic
def create(opts={})
Request::Xml.put(topic_path) do |request|
msg_options = {
MaximumMessageSize: 65536
}.merge(opts)
request.content :Topic, msg_options
end
end
# 删除topic
def delete
Request::Xml.delete(topic_path)
end
# 获取topic属性
def get_topic_attributes
topic_hash = Hash.from_xml(Request::Xml.get(topic_path))
{
topic_name: topic_hash["Topic"]["TopicName"],
create_time: topic_hash["Topic"]["CreateTime"],
last_modify_time: topic_hash["Topic"]["LastModifyTime"],
maximum_message_size: topic_hash["Topic"]["MaximumMessageSize"],
message_retention_period: topic_hash["Topic"]["MessageRetentionPeriod"],
message_ount: topic_hash["Topic"]["MessageCount"],
logging_enabled: topic_hash["Topic"]["LoggingEnabled"]
}
end
#订阅topic
def subscribe(opts = {})
if opts[:Endpoint].nil? || opts[:Endpoint].blank?
raise Request::XmlException.new(Exception.new("subscribe parameters invalid"))
else
Request::Xml.put(subscribe_path) do |request|
request.content(:Subscription, opts)
end
end
end
#退订topic
def unsubscribe
Request::Xml.delete(subscribe_path)
end
#发布消息
def publish_message(opts = {})
if opts[:MessageBody].nil? || opts[:MessageBody].blank?
raise Exception.new("publish message parameters invalid")
else
Request::Xml.post(message_path) do |request|
request.content(:Message, opts)
end
end
end
private
def topic_path
"/topics/#{name}"
end
def subscribe_path
"/topics/#{name}/subscriptions/#{subscription_name}"
end
def message_path
"/topics/#{name}/messages"
end
end
end
|
insub/aliyun_iot
|
lib/aliyun_iot.rb
|
require 'active_support'
require 'active_support/core_ext'
require 'rest-client'
require 'nokogiri'
require 'yaml'
require 'openssl'
require "aliyun_iot/version"
require "aliyun_iot/queue"
require "aliyun_iot/topic"
require "aliyun_iot/message"
require "aliyun_iot/product"
require "aliyun_iot/result"
class Hash
def self.xml_array content, *path
o = xml_object(content, *path)
return (o.is_a?(Array) ? o : [o]).reject { |n| n.empty? }
end
def self.xml_object content, *path
h = from_xml(content)
path.reduce(h) { |memo, node| memo = memo[node] || {} }
end
end
module AliyunIot
class << self
def configuration
@configuration ||= begin
if defined? Rails
config_file = Rails.root.join("config/aliyun_iot.yml")
else
config_file = File.expand_path('../../config/aliyun_iot.yml', __FILE__)
end
if (File.exist?(config_file))
config = YAML.load(ERB.new(File.new(config_file).read).result)
config = config[Rails.env] if defined? Rails
end
OpenStruct.new(config || {access_id: "", key: "", region: "", product_key: "", owner_id: ""})
end
end
def configure
yield(configuration)
end
end
end
|
emclab/post_boardx
|
config/routes.rb
|
PostBoardx::Engine.routes.draw do
end
|
emclab/post_boardx
|
test/post_boardx_test.rb
|
require 'test_helper'
class PostBoardxTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, PostBoardx
end
end
|
emclab/post_boardx
|
lib/post_boardx.rb
|
<filename>lib/post_boardx.rb<gh_stars>0
require "post_boardx/engine"
module PostBoardx
end
|
majesty2450/whip
|
lib/whip/compile-option.rb
|
require_relative "cli/option"
require_relative "cli/flag"
require_relative "cli/argument"
require_relative "cli/parser"
require_relative "file"
require_relative "compiler"
module Whip end
module Whip::CLI end
# Option...
class Whip::CLI::CompileOption < Whip::CLI::Option
def initialize
super([
Whip::CLI::Flag.new("-c"),
Whip::CLI::Flag.new("--compile")],
"compiles input as whip and outputs as html",
true)
end
def action (matches, parser)
if @args.length == 0
print "Error: Missing args ("
@flags.each do |flag|
print flag.name + " "
end
puts ")"
else
output = nil
matches.each do |match|
if match.match(Whip::CLI::Flag.new("-o"))
output = match
end
end
compiler = Whip::Compiler.new
if output
@args.each_with_index do |arg, index|
if output.args.length > index
compiler.compile(Whip::File.new(arg.value, output.args[index].value))
else
compiler.compile(Whip::File.new(arg.value))
end
end
else
@args.each do |arg|
compiler.compile(Whip::File.new(arg.value))
end
end
end
end
end
|
majesty2450/whip
|
lib/whip/compiler.rb
|
require_relative "file"
require_relative "parser"
require_relative "token"
require_relative "text-token"
require_relative "command-token"
module Whip end
# Compiles a given file to an output
class Whip::Compiler
def initialize
end
def compile (file, tokens = Whip::Parser.new.parse(file))
deps = Array.new
File.open(file.output_path, "w") do |fout|
tokens.each do |token|
case token
when Whip::TextToken
# copy
File.open(file.path, "r") do |fin|
fin.seek(token.starts - 1, IO::SEEK_SET)
while fin.pos < token.ends - 1
fout.syswrite(fin.getc)
end
end
when Whip::CommandToken
case token.name
when "include"
deps.push(token.argument)
File.open(file.dir + token.argument, "r") do |fin|
while fin.eof? == false
c = fin.getc
if c == "\n"
fout.syswrite("\n" + " " * token.indent)
else
fout.syswrite(c)
end
end
fout.syswrite("\n")
end
end
end
end
end
return deps
end
end
|
majesty2450/whip
|
lib/whip/output-option.rb
|
require_relative "cli/option"
require_relative "cli/flag"
require_relative "cli/argument"
require_relative "cli/parser"
require_relative "file"
module Whip end
module Whip::CLI end
# Option...
class Whip::CLI::OutputOption < Whip::CLI::Option
def initialize
super([
Whip::CLI::Flag.new("-o"),
Whip::CLI::Flag.new("--output")],
"defines the compiled output paths",
false)
end
def action (matches, parser)
if @args.length == 0
print "Error: Missing args ("
@flags.each do |flag|
print flag.name + " "
end
puts ")"
end
end
end
|
majesty2450/whip
|
lib/whip/watch.rb
|
require_relative "file"
module Whip end
# A bundle for watching whip files
class Whip::Watch
def initialize (file)
@file = file
@deps = Array.new
@file_mod = File::mtime(file.path)
@deps_mod = Array.new
end
def changeDeps (deps)
@deps = deps
@deps_mod = Array.new
@deps.each do |dep|
@deps_mod.push(File::mtime(file.dir + dep))
end
end
def modified
@file_mod = File::mtime(@file.path)
end
def check
change = false
if @file_mod != File::mtime(@file.path)
change = true
end
for i in 0...@deps.length
mod = File::mtime(file.dir + @deps[i])
if @deps_mod[i] != mod
@deps_mod[i] = mod
change = true
end
end
return change
end
def file
@file
end
end
|
majesty2450/whip
|
lib/whip.rb
|
<filename>lib/whip.rb
require_relative "whip/cli/parser"
require_relative "whip/cli/version-option"
require_relative "whip/cli/help-option"
require_relative "whip/output-option"
require_relative "whip/compile-option"
require_relative "whip/watch-option"
module Whip end
module Whip::CLI end
###############################################################################
#
###############################################################################
trap("INT") do
interrupted = true
puts "Exiting..."
exit
end
Whip::CLI::Parser.new([
Whip::CLI::VersionOption.new("0.1.0"),
Whip::CLI::HelpOption.new,
Whip::CLI::OutputOption.new,
Whip::CLI::CompileOption.new,
Whip::CLI::WatchOption.new
])
.parse
|
majesty2450/whip
|
lib/whip/watch-option.rb
|
require_relative "cli/option"
require_relative "cli/flag"
require_relative "cli/argument"
require_relative "cli/parser"
require_relative "file"
require_relative "watcher"
module Whip end
module Whip::CLI end
# Option...
class Whip::CLI::WatchOption < Whip::CLI::Option
def initialize
super([
Whip::CLI::Flag.new("-w"),
Whip::CLI::Flag.new("--watch")],
"recompiles files on dependency or file modification",
true)
end
def action (matches, parser)
if @args.length == 0
print "Error: Missing args ("
@flags.each do |flag|
print flag.name + " "
end
puts ")"
else
output = nil
matches.each do |match|
if match.match(Whip::CLI::Flag.new("-o"))
output = match
end
end
files = Array.new
@args.each_with_index do |arg, index|
if output && output.args.length > index
files.push(Whip::File.new(arg.value, output.args[index].value))
else
files.push(Whip::File.new(arg.value))
end
end
watcher = Whip::Watcher.new(files)
watcher.watch
end
end
end
|
majesty2450/whip
|
whip.gemspec
|
<reponame>majesty2450/whip
Gem::Specification.new do |s|
s.name = 'whip'
s.version = '0.1.0'
s.executables << "whip"
s.date = '2015-09-15'
s.summary = "whip: html inclusion preprocessor."
s.description = "A html preprocessor that compile .whip files into .html files."
s.authors = ["<NAME>"]
s.email = 'none'
s.files = Dir['lib/*.rb'] + Dir['lib/whip/*.rb'] + Dir['lib/whip/cli/*.rb'] + Dir['bin/*'] + Dir['test/**/*']
#s.homepage = 'none'
s.license = 'MIT'
end
|
majesty2450/whip
|
lib/whip/command-token.rb
|
<filename>lib/whip/command-token.rb
require_relative "token"
module Whip end
# All commands appear in the same way
class Whip::CommandToken < Whip::Token
def initialize (pos)
super(pos)
@name = ""
@argument = ""
@indent = 0
end
def name= (name)
@name = name
end
def argument= (arg)
@argument = arg
end
def name
@name
end
def argument
@argument
end
def indent= (indent)
@indent = indent
end
def indent
@indent
end
end
|
majesty2450/whip
|
lib/whip/text-token.rb
|
require_relative "token"
module Whip end
# Text that is not part of a command
class Whip::TextToken < Whip::Token
def initialize (pos)
super(pos)
end
end
|
majesty2450/whip
|
lib/whip/file.rb
|
module Whip end
# A file has a path, an output path for compile, and a list of dependencies
class Whip::File
def initialize (path, output_path = "")
@path = path
if output_path == ""
if path.rindex(".")
@output_path = path[0..path.rindex(".")] + "html"
else
@output_path = path + ".html"
end
else
@output_path = output_path
end
@dependencies = Array.new
end
def path
@path
end
def output_path
@output_path
end
def setOutputPath (output_path, destroy)
if destroy
File.delete(@output_path)
end
@output_path = output_path
end
def dir
directory = ""
loop do
if @path.rindex("/")
directory = @path[0..@path.rindex("/")]
else
directory = "./"
end
break if File.directory?(directory)
end
return directory
end
end
|
majesty2450/whip
|
lib/whip/indexer.rb
|
<filename>lib/whip/indexer.rb
require_relative "file"
module Whip end
# Indexes a directory to create a list of compilable files
class Whip::Indexer
def initialize
end
# TODO: see parsing with errors and non-whip files for greater indexer
# support
def index (path = ".")
files = Array.new
# search path and fill with files
Dir.foreach(path) do |entry|
if File.file?(path + "/" + entry)
if entry.length > 5 && entry[-5..-1] == ".whip"
files.push(Whip::File.new(path + "/" + entry, path + "/" + entry[0...entry.rindex(".")] + ".html"))
end
end
end
return files
end
end
|
majesty2450/whip
|
lib/whip/cli/version-option.rb
|
<gh_stars>0
require_relative "option"
require_relative "flag"
require_relative "argument"
require_relative "parser"
module Whip end
module Whip::CLI end
###############################################################################
#
###############################################################################
class Whip::CLI::VersionOption < Whip::CLI::Option
def initialize (version)
super([
Whip::CLI::Flag.new("-v"),
Whip::CLI::Flag.new("--version")],
"displays version number",
true)
@version = version
end
def action (matches, parser)
puts "Version: " + @version
end
end
|
majesty2450/whip
|
lib/whip/parser.rb
|
require_relative "file"
require_relative "token"
require_relative "text-token"
require_relative "command-token"
module Whip end
# Parses a given file by first tokenizing the string, then parsing and
# executing the command
class Whip::Parser
module TokenStates
TEXT_STATE = 0
COMMAND_OPEN_STATE = 1
COMMAND_NAME_STATE = 2
COMMAND_ARGUMENT_STATE = 3
COMMAND_ARGUMENT_START_STATE = 4
COMMAND_CLOSE_STATE = 5
end
def initialize
end
# TODO: fix parse so as to work with errors properly
def parse (file)
File.open(file.path, "r") do |file|
# read each char and use state
tokens = Array.new
state = TokenStates::TEXT_STATE
input = ""
last_newline = 0
while file.eof? == false
case state
when TokenStates::TEXT_STATE
#puts "TEXT_STATE"
input = file.getc
if input == "<"
state = TokenStates::COMMAND_OPEN_STATE
elsif input == "\n"
last_newline = file.pos
else
if tokens.length == 0 || tokens.last.class != Whip::TextToken
tokens.push(Whip::TextToken.new(file.pos))
end
end
when TokenStates::COMMAND_OPEN_STATE
#puts "COMMAND_OPEN_STATE"
pos = file.pos
input += file.getc
input += file.getc
input += file.getc
input += file.getc
if input == "<!--$"
state = TokenStates::COMMAND_NAME_STATE
if tokens.last.class != Whip::CommandToken
tokens.last.ends = pos
end
tokens.push(Whip::CommandToken.new(pos))
tokens.last.indent = pos - last_newline - 1
input = ""
else
state = TokenStates::TEXT_STATE
if tokens.length == 0
tokens.push(Whip::TextToken.new(pos))
end
end
when TokenStates::COMMAND_NAME_STATE
#puts "COMMAND_NAME_STATE"
input += file.getc
if input[-1] == " "
state = TokenStates::COMMAND_ARGUMENT_START_STATE
tokens.last.name = input[0...-1]
input = ""
end
when TokenStates::COMMAND_ARGUMENT_START_STATE
#puts "COMMAND_ARGUMENT_START_STATE"
input = file.getc
if input == '"'
state = TokenStates::COMMAND_ARGUMENT_STATE
input = ""
end
when TokenStates::COMMAND_ARGUMENT_STATE
#puts "COMMAND_ARGUMENT_STATE"
input += file.getc
if input[-1] == '"'
state = TokenStates::COMMAND_CLOSE_STATE
tokens.last.argument = input[0...-1]
input = ""
end
when TokenStates::COMMAND_CLOSE_STATE
#puts "COMMAND_CLOSE_STATE"
input += file.getc
if input.strip == "-->"
state = TokenStates::TEXT_STATE
tokens.last.ends = file.pos
input = ""
end
else
end
end
tokens.last.ends = file.pos + 1
return tokens
end
end
end
|
majesty2450/whip
|
lib/whip/cli/help-option.rb
|
<reponame>majesty2450/whip
require_relative "option"
require_relative "flag"
require_relative "argument"
require_relative "parser"
module Whip end
module Whip::CLI end
###############################################################################
#
###############################################################################
class Whip::CLI::HelpOption < Whip::CLI::Option
def initialize
super([
Whip::CLI::Flag.new("-h"),
Whip::CLI::Flag.new("--help")],
"displays useage information",
true)
end
def action (matches, parser)
if @args.length > 0 # TODO: fix spacing on args
puts "Useage: "
args.each do |arg|
parser.options.each do |option|
print "\t"
use_option = false
option.flags.each do |flag|
if arg.value == flag.name[1..-1] || arg.value == flag.name[2..-1]
print flag.name + " "
use_option = true
end
end
if use_option
puts "\t" + option.description
end
end
end
else
puts "Useage:"
parser.options.each do |option|
print "\t"
option.flags.each do |flag|
print flag.name + " "
end
puts "\t" + option.description
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.