repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/rebuild.rb
lib/vagrant-linode/commands/rebuild.rb
require 'optparse' module VagrantPlugins module Linode module Commands class Rebuild < Vagrant.plugin('2', :command) def execute opts = OptionParser.new do |o| o.banner = 'Usage: vagrant rebuild [vm-name]' end argv = parse_options(opts) with_target_vms(argv) do |machine| machine.action(:rebuild) end 0 end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/create_image.rb
lib/vagrant-linode/commands/create_image.rb
module VagrantPlugins module Linode module Commands class CreateImage < Vagrant.plugin('2', :command) def execute options = {} opts = OptionParser.new do |o| o.banner = 'Usage: vagrant linode images create [options]' end argv = parse_options(opts) return unless argv with_target_vms(argv, provider: :linode) do |machine| machine.action('create_image') end end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/networks.rb
lib/vagrant-linode/commands/networks.rb
module VagrantPlugins module Linode module Commands class Networks < Vagrant.plugin('2', :command) def execute options = {} opts = OptionParser.new do |o| o.banner = 'Usage: vagrant linode networks [options]' end argv = parse_options(opts) return unless argv with_target_vms(argv, provider: :linode) do |machine| machine.action('list_networks') end end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/list_images.rb
lib/vagrant-linode/commands/list_images.rb
module VagrantPlugins module Linode module Commands class ListImages < Vagrant.plugin('2', :command) def execute options = {} opts = OptionParser.new do |o| o.banner = 'Usage: vagrant linode images list [options]' end argv = parse_options(opts) return unless argv with_target_vms(argv, provider: :linode) do |machine| machine.action('list_images') end end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/root.rb
lib/vagrant-linode/commands/root.rb
require 'vagrant-linode/actions' module VagrantPlugins module Linode module Commands class Root < Vagrant.plugin('2', :command) def self.synopsis 'query Linode for available images or plans' end def initialize(argv, env) @main_args, @sub_command, @sub_args = split_main_and_subcommand(argv) @subcommands = Vagrant::Registry.new @subcommands.register(:images) do require File.expand_path('../images', __FILE__) Images end @subcommands.register(:plans) do require File.expand_path('../plans', __FILE__) Plans end @subcommands.register(:distributions) do require File.expand_path('../distributions', __FILE__) Distributions end @subcommands.register(:kernels) do require File.expand_path('../kernels', __FILE__) Kernels end @subcommands.register(:datacenters) do require File.expand_path('../datacenters', __FILE__) Datacenters end @subcommands.register(:networks) do require File.expand_path('../networks', __FILE__) Networks end @subcommands.register(:servers) do require File.expand_path('../servers', __FILE__) Servers end @subcommands.register(:volumes) do require File.expand_path('../volumes', __FILE__) Volumes end super(argv, env) end def execute if @main_args.include?('-h') || @main_args.include?('--help') # Print the help for all the linode commands. return help end command_class = @subcommands.get(@sub_command.to_sym) if @sub_command return help if !command_class || !@sub_command @logger.debug("Invoking command class: #{command_class} #{@sub_args.inspect}") # Initialize and execute the command class command_class.new(@sub_args, @env).execute end def help opts = OptionParser.new do |opts| opts.banner = 'Usage: vagrant linode <subcommand> [<args>]' opts.separator '' opts.separator 'Available subcommands:' # Add the available subcommands as separators in order to print them # out as well. keys = [] @subcommands.each { |key, _value| keys << key.to_s } keys.sort.each do |key| opts.separator " #{key}" end opts.separator '' opts.separator 'For help on any individual subcommand run `vagrant linode <subcommand> -h`' end @env.ui.info(opts.help, prefix: false) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/plans.rb
lib/vagrant-linode/commands/plans.rb
module VagrantPlugins module Linode module Commands class Plans < Vagrant.plugin('2', :command) def execute options = {} opts = OptionParser.new do |o| o.banner = 'Usage: vagrant linode plans [options]' end argv = parse_options(opts) return unless argv with_target_vms(argv, provider: :linode) do |machine| machine.action('list_plans') end end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/kernels.rb
lib/vagrant-linode/commands/kernels.rb
module VagrantPlugins module Linode module Commands class Kernels < Vagrant.plugin('2', :command) def execute options = {} opts = OptionParser.new do |o| o.banner = 'Usage: vagrant linode kernels [options]' end argv = parse_options(opts) return unless argv with_target_vms(argv, provider: :linode) do |machine| machine.action('list_kernels') end end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/distributions.rb
lib/vagrant-linode/commands/distributions.rb
module VagrantPlugins module Linode module Commands class Distributions < Vagrant.plugin('2', :command) def execute options = {} opts = OptionParser.new do |o| o.banner = 'Usage: vagrant linode distributions [options]' end argv = parse_options(opts) return unless argv with_target_vms(argv, provider: :linode) do |machine| machine.action('list_distributions') end end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/images.rb
lib/vagrant-linode/commands/images.rb
module VagrantPlugins module Linode module Commands class Images < Vagrant.plugin('2', :command) def initialize(argv, env) @main_args, @sub_command, @sub_args = split_main_and_subcommand(argv) @subcommands = Vagrant::Registry.new @subcommands.register(:list) do require File.expand_path('../list_images', __FILE__) ListImages end @subcommands.register(:create) do require File.expand_path('../create_image', __FILE__) CreateImage end super(argv, env) end def execute if @main_args.include?('-h') || @main_args.include?('--help') # Print the help for all the rackspace commands. return help end command_class = @subcommands.get(@sub_command.to_sym) if @sub_command return help if !command_class || !@sub_command @logger.debug("Invoking command class: #{command_class} #{@sub_args.inspect}") # Initialize and execute the command class command_class.new(@sub_args, @env).execute end def help opts = OptionParser.new do |opts| opts.banner = 'Usage: vagrant linode images <subcommand> [<args>]' opts.separator '' opts.separator 'Available subcommands:' # Add the available subcommands as separators in order to print them # out as well. keys = [] @subcommands.each { |key, _value| keys << key.to_s } keys.sort.each do |key| opts.separator " #{key}" end opts.separator '' opts.separator 'For help on any individual subcommand run `vagrant linode images <subcommand> -h`' end @env.ui.info(opts.help, prefix: false) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/commands/volumes.rb
lib/vagrant-linode/commands/volumes.rb
module VagrantPlugins module Linode module Commands class Volumes < Vagrant.plugin('2', :command) def initialize(argv, env) @main_args, @sub_command, @sub_args = split_main_and_subcommand(argv) @subcommands = Vagrant::Registry.new @subcommands.register(:list) do require File.expand_path('../list_volumes', __FILE__) ListVolumes end super(argv, env) end def execute if @main_args.include?('-h') || @main_args.include?('--help') # Print the help for all the rackspace commands. return help end command_class = @subcommands.get(@sub_command.to_sym) if @sub_command return help if !command_class || !@sub_command @logger.debug("Invoking command class: #{command_class} #{@sub_args.inspect}") # Initialize and execute the command class command_class.new(@sub_args, @env).execute end def help opts = OptionParser.new do |opts| opts.banner = 'Usage: vagrant linode volumes <subcommand> [<args>]' opts.separator '' opts.separator 'Available subcommands:' # Add the available subcommands as separators in order to print them # out as well. keys = [] @subcommands.each { |key, _value| keys << key.to_s } keys.sort.each do |key| opts.separator " #{key}" end opts.separator '' opts.separator 'For help on any individual subcommand run `vagrant linode volumes <subcommand> -h`' end @env.ui.info(opts.help, prefix: false) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/read_state.rb
lib/vagrant-linode/actions/read_state.rb
module VagrantPlugins module Linode module Actions class ReadState def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant_linode::action::read_state') end def call(env) env[:machine_state] = read_state(env[:linode_api], @machine) @logger.info "Machine state is '#{env[:machine_state]}'" @app.call(env) end def read_state(_linode, machine) return :not_created if machine.id.nil? server = Provider.linode(machine) return :not_created if server.nil? status = server[:status] return :not_created if status.nil? states = { '' => :not_created, '-2' => :boot_failed, '-1' => :being_created, '0' => :brand_new, '1' => :active, # running '2' => :off, # powered off '3' => :shutting_down } states[status.to_s] end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/message_already_off.rb
lib/vagrant-linode/actions/message_already_off.rb
module VagrantPlugins module Linode module Actions class MessageAlreadyOff def initialize(app, env) @app = app end def call(env) env[:ui].info(I18n.t("vagrant_linode.info.already_off", :status => :off)) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/reload.rb
lib/vagrant-linode/actions/reload.rb
require 'vagrant-linode/helpers/client' require 'vagrant-linode/helpers/waiter' module VagrantPlugins module Linode module Actions class Reload include Helpers::Waiter def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::reload') end def call(env) @client = env[:linode_api] # submit reboot linode request result = @client.linode.reboot(linodeid: @machine.id) # wait for request to complete env[:ui].info I18n.t('vagrant_linode.info.reloading') wait_for_event(env, result['jobid']) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/is_created.rb
lib/vagrant-linode/actions/is_created.rb
module VagrantPlugins module Linode module Actions class IsCreated def initialize(app, _env) @app = app end def call(env) env[:result] = env[:machine].state.id != :not_created @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/list_volumes.rb
lib/vagrant-linode/actions/list_volumes.rb
module VagrantPlugins module Linode module Actions class ListVolumes def initialize(app, _env) @app = app end def call(env) api = env[:linode_api] logger = env[:ui] machine = env[:machine] remote_volumes = api.volume.list volume_definitions = machine.provider_config.volumes volume_definitions.each do |volume| volume_label = "#{machine.name}_#{volume[:label]}" remote_volume = remote_volumes.find { |v| v.label == volume_label } if remote_volume.nil? logger.info format_volume(volume_label, "does not exist") next end logger.info format_volume(volume_label, volume_state(machine, remote_volume)) end @app.call(env) end private def volume_state(machine, volume) if volume.linodeid.to_s == machine.id "attached" elsif volume.linodeid == 0 "detached" else "attached to other VM" end end def format_volume(label, state) "volume \"%s\": %s" % [label, state] end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/rebuild.rb
lib/vagrant-linode/actions/rebuild.rb
require 'vagrant-linode/helpers/client' require 'vagrant-linode/helpers/normalizer' require 'vagrant-linode/helpers/waiter' require 'vagrant-linode/errors' require 'vagrant-linode/services/volume_manager' module VagrantPlugins module Linode module Actions class Rebuild include Vagrant::Util::Retryable include VagrantPlugins::Linode::Helpers::Normalizer include VagrantPlugins::Linode::Helpers::Waiter def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::rebuild') end def call(env) @client = env[:linode_api] ssh_key_id = env[:machine].config.ssh.private_key_path ssh_key_id = ssh_key_id[0] if ssh_key_id.is_a?(Array) if ssh_key_id pubkey = File.read(File.expand_path("#{ssh_key_id}.pub")) end if @machine.provider_config.root_pass root_pass = @machine.provider_config.root_pass else root_pass = Digest::SHA2.new.update(@machine.provider_config.api_key).to_s end if @machine.provider_config.stackscript stackscripts = @client.stackscript.list + @client.avail.stackscripts stackscript = stackscripts.find { |s| s.label.downcase == @machine.provider_config.stackscript.to_s.downcase } fail(Errors::StackscriptMatch, stackscript: @machine.provider_config.stackscript.to_s) if stackscript.nil? stackscript_id = stackscript.stackscriptid || nil else stackscript_id = @machine.provider_config.stackscriptid end stackscript_udf_responses = @machine.provider_config.stackscript_udf_responses if stackscript_udf_responses and !stackscript_udf_responses.is_a?(Hash) fail(Errors::StackscriptUDFFormat, format: stackscript_udf_responses.class.to_s) else stackscript_udf_responses = @machine.provider_config.stackscript_udf_responses or {} end if @machine.provider_config.distribution distributions = @client.avail.distributions distribution = distributions.find { |d| d.label.downcase.include? @machine.provider_config.distribution.downcase } fail(Errors::DistroMatch, distro: @machine.provider_config.distribution.to_s) if distribution.nil? distribution_id = distribution.distributionid || nil else distribution_id = @machine.provider_config.distributionid end if @machine.provider_config.imageid distribution_id = nil images = @client.image.list image = images.find { |i| i.imageid == @machine.provider_config.imageid } fail Errors::ImageMatch, image: @machine.provider_config.imageid.to_s if image.nil? image_id = image.imageid || nil elsif @machine.provider_config.image distribution_id = nil images = @client.image.list image = images.find { |i| i.label.downcase.include? @machine.provider_config.image.downcase } fail Errors::ImageMatch, image: @machine.provider_config.image.to_s if image.nil? image_id = image.imageid || nil end if @machine.provider_config.kernel kernels = @client.avail.kernels(isxen: nil, iskvm: 1) kernel = kernels.find { |k| k.label.downcase.include? @machine.provider_config.kernel.downcase } raise( Errors::KernelMatch, kernel: @machine.provider_config.kernel.to_s ) if kernel == nil kernel_id = kernel.kernelid || nil else kernel_id = @machine.provider_config.kernelid end if @machine.provider_config.datacenter datacenters = @client.avail.datacenters datacenter = datacenters.find { |d| d.abbr == @machine.provider_config.datacenter } fail Errors::DatacenterMatch, datacenter: @machine.provider_config.datacenter if datacenter.nil? datacenter_id = datacenter.datacenterid else datacenters = @client.avail.datacenters datacenter = datacenters.find { |d| d.datacenterid == @machine.provider_config.datacenterid } fail Errors::DatacenterMatch, datacenter: @machine.provider_config.datacenter if datacenter.nil? datacenter_id = datacenter.datacenterid end if @machine.provider_config.plan plan_label = normalize_plan_label(@machine.provider_config.plan) plans = @client.avail.linodeplans plan = plans.find { |p| p.label.include? plan_label } fail Errors::PlanID, plan: @machine.provider_config.plan if plan.nil? plan_id = plan.planid else plans = @client.avail.linodeplans plan = plans.find { |p| p.planid.to_i == @machine.provider_config.planid.to_i } fail Errors::PlanID, plan: @machine.provider_config.planid if plan.nil? plan_id = @machine.provider_config.planid end ### Disk Images xvda_size, swap_size, disk_sanity = @machine.provider_config.xvda_size, @machine.provider_config.swap_size, true # Sanity checks for disk size if xvda_size != true disk_sanity = false if ( xvda_size.to_i + swap_size.to_i) > ( plan['disk'].to_i * 1024) end # throw if disk sizes are too large if xvda_size == true xvda_size = ( ( plan['disk'].to_i * 1024) - swap_size.to_i) elsif disk_sanity == false fail Errors::DiskSize, current: (xvda_size.to_i + swap_size.to_i), max: ( plan['disk'].to_i * 1024) end env[:ui].info I18n.t('vagrant_linode.info.powering_off') shutdownjob = @client.linode.shutdown( linodeid: @machine.id ) wait_for_event(env, shutdownjob['jobid']) env[:ui].info I18n.t('vagrant_linode.info.destroying') diskList = @client.linode.disk.list( linodeid: @machine.id ) diskList.each do |diskEntry| diskDeleteResult = @client.linode.disk.delete( linodeid: @machine.id, diskid: diskEntry['diskid'] ) job = diskDeleteResult['jobid'] jobStatus = @client.linode.job.list( linodeid: @machine.id, jobid: job ) while jobStatus[0]['host_finish_dt'].nil? || jobStatus[0]['host_finish_dt'].empty? do sleep(5) jobStatus = @client.linode.job.list( linodeid: @machine.id, jobid: job ) end end configList = @client.linode.config.list( linodeid: @machine.id ) configList.each do |configEntry| configDeleteResult = @client.linode.config.delete( linodeid: @machine.id, configid: configEntry['configid'] ) end env[:ui].info I18n.t('vagrant_linode.info.creating') if stackscript_id swap = @client.linode.disk.create( linodeid: @machine.id, label: 'Vagrant swap', type: 'swap', size: swap_size ) disk = @client.linode.disk.createfromstackscript( linodeid: @machine.id, stackscriptid: stackscript_id, stackscriptudfresponses: JSON.dump(stackscript_udf_responses), distributionid: distribution_id, label: 'Vagrant Disk Distribution ' + distribution_id.to_s + ' Linode ' + @machine.id.to_s, type: 'ext4', size: xvda_size, rootsshkey: pubkey, rootpass: root_pass ) elsif distribution_id swap = @client.linode.disk.create( linodeid: @machine.id, label: 'Vagrant swap', type: 'swap', size: swap_size ) disk = @client.linode.disk.createfromdistribution( linodeid: @machine.id, distributionid: distribution_id, label: 'Vagrant Disk Distribution ' + distribution_id.to_s + ' Linode ' + @machine.id.to_s, type: 'ext4', size: xvda_size, rootsshkey: pubkey, rootpass: root_pass ) elsif image_id disk = @client.linode.disk.createfromimage( linodeid: @machine.id, imageid: image_id, label: 'Vagrant Disk Image (' + image_id.to_s + ') for ' + @machine.id.to_s, size: xvda_size, rootsshkey: pubkey, rootpass: root_pass ) swap = @client.linode.disk.create( linodeid: @machine.id, label: 'Vagrant swap', type: 'swap', size: swap_size ) end config = @client.linode.config.create( linodeid: @machine.id, label: 'Vagrant Config', disklist: "#{disk['diskid']},#{swap['diskid']}", kernelid: kernel_id ) # @todo: allow provisioning to set static configuration for networking if @machine.provider_config.private_networking private_network = @client.linode.ip.addprivate linodeid: @machine.id end label = @machine.provider_config.label label = label || @machine.name if @machine.name != 'default' label = label || get_server_name group = @machine.provider_config.group group = "" if @machine.provider_config.group == false Services::VolumeManager.new(@machine, @client.volume, env[:ui]).perform result = @client.linode.update( linodeid: @machine.id, label: label, lpm_displaygroup: group ) env[:ui].info I18n.t('vagrant_linode.info.booting', linodeid: @machine.id) bootjob = @client.linode.boot linodeid: @machine.id # sleep 1 until ! @client.linode.job.list(:linodeid => @machine.id, :jobid => bootjob['jobid'], :pendingonly => 1).length wait_for_event(env, bootjob['jobid']) # refresh linode state with provider and output ip address linode = Provider.linode(@machine, refresh: true) public_network = linode.network.find { |network| network['ispublic'] == 1 } env[:ui].info I18n.t('vagrant_linode.info.linode_ip', ip: public_network['ipaddress']) if private_network env[:ui].info I18n.t('vagrant_linode.info.linode_private_ip', ip: private_network['ipaddress']) end # wait for ssh to be ready switch_user = @machine.provider_config.setup? user = @machine.config.ssh.username if switch_user @machine.config.ssh.username = 'root' @machine.config.ssh.password = root_pass end retryable(tries: 25, sleep: 10) do # @todo bump tries when this is solid next if env[:interrupted] fail 'not ready' unless @machine.communicate.ready? end @machine.config.ssh.username = user @app.call(env) end def get_server_name "vagrant_linode-#{rand.to_s.split('.')[1]}" end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/message_not_created.rb
lib/vagrant-linode/actions/message_not_created.rb
module VagrantPlugins module Linode module Actions class MessageNotCreated def initialize(app, env) @app = app end def call(env) env[:ui].info(I18n.t("vagrant_linode.info.not_created", :status => :not_created)) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/connect_linode.rb
lib/vagrant-linode/actions/connect_linode.rb
require 'log4r' require "vagrant-linode/client_wrapper" module VagrantPlugins module Linode module Actions # This action connects to Linode, verifies credentials work, and # puts the Linode connection object into the `:linode_api` key # in the environment. class ConnectLinode def initialize(app, _env) @app = app @logger = Log4r::Logger.new('vagrant_linode::action::connect_linode') end def call(env) # Get the configs config = env[:machine].provider_config api_key = config.api_key api_url = config.api_url params = { apikey: api_key, endpoint: api_url } @logger.info('Connecting to Linode api_url...') linode = ClientWrapper.new(::LinodeAPI::Retryable.new(params), env[:ui]) env[:linode_api] = linode @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/power_on.rb
lib/vagrant-linode/actions/power_on.rb
require 'vagrant-linode/helpers/client' require 'vagrant-linode/helpers/waiter' module VagrantPlugins module Linode module Actions class PowerOn include Helpers::Waiter def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::power_on') end def call(env) @client = env[:linode_api] # submit power on linode request result = @client.linode.boot(linodeid: @machine.id) # wait for request to complete env[:ui].info I18n.t('vagrant_linode.info.powering_on') wait_for_event(env, result['jobid']) # refresh linode state with provider Provider.linode(@machine, refresh: true) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/list_servers.rb
lib/vagrant-linode/actions/list_servers.rb
module VagrantPlugins module Linode module Actions class ListServers def initialize(app, _env) @app = app end def call(env) linode_api = env[:linode_api] env[:ui].info ('%-8s %-30s %-20s %-10s %-9s' % ['LinodeID', 'Label', 'DataCenter', 'Plan', 'Status']) linode_api.linode.list.sort_by(&:imageid).each do |ln| env[:ui].info ('%-8s %-30s %-20s %-10s %-9s' % [ln.linodeid, ln.label, ln.datacenterid, ln.planid, ln.status]) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/list_datacenters.rb
lib/vagrant-linode/actions/list_datacenters.rb
module VagrantPlugins module Linode module Actions class ListDatacenters def initialize(app, _env) @app = app end def call(env) linode_api = env[:linode_api] env[:ui].info ('%-15s %-36s %s' % ['Datacenter ID', 'Location', 'Abbr']) linode_api.avail.datacenters.sort_by(&:datacenterid).each do |dc| env[:ui].info ('%-15s %-36s %s' % [dc.datacenterid, dc.location, dc.abbr]) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/setup_sudo.rb
lib/vagrant-linode/actions/setup_sudo.rb
module VagrantPlugins module Linode module Actions class SetupSudo def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::setup_sudo') end def call(env) # check if setup is enabled return @app.call(env) unless @machine.provider_config.setup? # override ssh username to root user = @machine.config.ssh.username @machine.config.ssh.username = 'root' # check for guest name available in Vagrant 1.2 first guest_name = @machine.guest.name if @machine.guest.respond_to?(:name) guest_name ||= @machine.guest.to_s.downcase case guest_name when /redhat/ env[:ui].info I18n.t('vagrant_linode.info.modifying_sudo') # disable tty requirement for sudo @machine.communicate.execute(<<-'BASH') sed -i'.bk' -e 's/\(Defaults\s\+requiretty\)/# \1/' /etc/sudoers BASH end # reset ssh username @machine.config.ssh.username = user @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/list_kernels.rb
lib/vagrant-linode/actions/list_kernels.rb
module VagrantPlugins module Linode module Actions class ListKernels def initialize(app, _env) @app = app end def call(env) linode_api = env[:linode_api] env[:ui].info ('%-4s %-6s %-6s %s' % ['ID', 'IsXen', 'IsKVM', 'Kernel Name']) linode_api.avail.kernels(isxen: nil, iskvm: 1).sort_by(&:kernelid).each do |kernel| env[:ui].info ('%-4s %-6s %-6s %s' % [kernel.kernelid, kernel.isxen, kernel.iskvm, kernel.label]) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/create_image.rb
lib/vagrant-linode/actions/create_image.rb
module VagrantPlugins module Linode module Actions class CreateImage def initialize(app, _env) @app = app @machine = _env[:machine] end def call(env) linode_api = env[:linode_api] env[:ui].info ('%-36s %-36s %-10s %-10s' % ['Image ID', 'Disk Label', 'Disk ID', 'Job ID']) linode_api.linode.disk.list(:linodeid => @machine.id).each do |disk| next if disk.type == 'swap' img = linode_api.linode.disk.imagize :linodeid => disk.linodeid, :diskid => disk.diskid, :description => 'Imagized with Vagrant' env[:ui].info ('%-36s %-36s %-10s %-10s' % [img.imageid, disk.label, disk.diskid, img.jobid]) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/message_already_active.rb
lib/vagrant-linode/actions/message_already_active.rb
module VagrantPlugins module Linode module Actions class MessageAlreadyActive def initialize(app, env) @app = app end def call(env) env[:ui].info(I18n.t("vagrant_linode.info.already_active", :status => :active)) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/modify_provision_path.rb
lib/vagrant-linode/actions/modify_provision_path.rb
module VagrantPlugins module Linode module Actions class ModifyProvisionPath def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::modify_provision_path') end def call(env) # check if provisioning is enabled enabled = true enabled = env[:provision_enabled] if env.key?(:provision_enabled) return @app.call(env) unless enabled username = @machine.ssh_info[:username] # change ownership of the provisioning path recursively to the # ssh user # # TODO submit patch to vagrant to set appropriate permissions # based on ssh username @machine.config.vm.provisioners.each do |provisioner| cfg = provisioner.config path = cfg.upload_path if cfg.respond_to? :upload_path path = cfg.provisioning_path if cfg.respond_to? :provisioning_path @machine.communicate.sudo("chown -R #{username} #{path}", error_check: false) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/list_images.rb
lib/vagrant-linode/actions/list_images.rb
module VagrantPlugins module Linode module Actions class ListImages def initialize(app, _env) @app = app end def call(env) linode_api = env[:linode_api] env[:ui].info ('%-10s %-22s %-10s %s' % ['Image ID', 'Created', 'Size (MB)', 'Image Label']) linode_api.image.list.sort_by(&:imageid).each do |img| env[:ui].info ('%-10s %-22s %-10s %s' % [img.imageid, img.create_dt, img.minsize, img.label]) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/setup_user.rb
lib/vagrant-linode/actions/setup_user.rb
module VagrantPlugins module Linode module Actions class SetupUser def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::setup_user') end def call(env) # check if setup is enabled return @app.call(env) unless @machine.provider_config.setup? # check if a username has been specified return @app.call(env) unless @machine.config.ssh.username # override ssh username to root temporarily user = @machine.config.ssh.username @machine.config.ssh.username = 'root' env[:ui].info I18n.t('vagrant_linode.info.creating_user', user: user) # create user account @machine.communicate.execute(<<-BASH) if ! (grep ^#{user}: /etc/passwd); then useradd -m -s /bin/bash #{user}; fi BASH # grant user sudo access with no password requirement @machine.communicate.execute(<<-BASH) if ! (grep #{user} /etc/sudoers); then echo "#{user} ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers; else sed -i -e "/#{user}/ s/=.*/=(ALL:ALL) NOPASSWD: ALL/" /etc/sudoers; fi BASH # create the .ssh directory in the users home @machine.communicate.execute("su #{user} -c 'mkdir -p ~/.ssh'") # add the specified key to the authorized keys file path = @machine.config.ssh.private_key_path path = path[0] if path.is_a?(Array) path = File.expand_path(path, @machine.env.root_path) pub_key = Linode.public_key(path) @machine.communicate.execute(<<-BASH) if ! grep '#{pub_key}' /home/#{user}/.ssh/authorized_keys; then echo '#{pub_key}' >> /home/#{user}/.ssh/authorized_keys; fi BASH # reset username @machine.config.ssh.username = user @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/list_plans.rb
lib/vagrant-linode/actions/list_plans.rb
module VagrantPlugins module Linode module Actions class ListPlans def initialize(app, _env) @app = app end def call(env) linode_api = env[:linode_api] env[:ui].info ('%-36s %s' % ['Plan ID', 'Plan Name']) linode_api.avail.linodeplans.sort_by(&:planid).each do |plan| env[:ui].info ('%-36s %s' % [plan.planid, plan.label]) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/is_stopped.rb
lib/vagrant-linode/actions/is_stopped.rb
module VagrantPlugins module Linode module Actions class IsStopped def initialize(app, _env) @app = app end def call(env) env[:result] = env[:machine].state.id == :off @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/create.rb
lib/vagrant-linode/actions/create.rb
require 'vagrant-linode/helpers/client' require 'vagrant-linode/helpers/normalizer' require 'vagrant-linode/helpers/waiter' require 'vagrant-linode/errors' require 'vagrant-linode/services/volume_manager' module VagrantPlugins module Linode module Actions class Create include Vagrant::Util::Retryable include VagrantPlugins::Linode::Helpers::Normalizer include VagrantPlugins::Linode::Helpers::Waiter def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::create') end def call(env) @client = env[:linode_api] ssh_key_id = env[:machine].config.ssh.private_key_path ssh_key_id = ssh_key_id[0] if ssh_key_id.is_a?(Array) if ssh_key_id pubkey = File.read(File.expand_path("#{ssh_key_id}.pub")) end if @machine.provider_config.root_pass root_pass = @machine.provider_config.root_pass else root_pass = Digest::SHA2.new.update(@machine.provider_config.api_key).to_s end if @machine.provider_config.stackscript stackscripts = @client.stackscript.list + @client.avail.stackscripts stackscript = stackscripts.find { |s| s.label.downcase == @machine.provider_config.stackscript.to_s.downcase } fail(Errors::StackscriptMatch, stackscript: @machine.provider_config.stackscript.to_s) if stackscript.nil? stackscript_id = stackscript.stackscriptid || nil else stackscript_id = @machine.provider_config.stackscriptid end stackscript_udf_responses = @machine.provider_config.stackscript_udf_responses if stackscript_udf_responses and !stackscript_udf_responses.is_a?(Hash) fail(Errors::StackscriptUDFFormat, format: stackscript_udf_responses.class.to_s) else stackscript_udf_responses = @machine.provider_config.stackscript_udf_responses or {} end if @machine.provider_config.distribution distributions = @client.avail.distributions distribution = distributions.find { |d| d.label.downcase.include? @machine.provider_config.distribution.downcase } fail(Errors::DistroMatch, distro: @machine.provider_config.distribution.to_s) if distribution.nil? distribution_id = distribution.distributionid || nil else distribution_id = @machine.provider_config.distributionid end if @machine.provider_config.imageid distribution_id = nil images = @client.image.list image = images.find { |i| i.imageid == @machine.provider_config.imageid } fail Errors::ImageMatch, image: @machine.provider_config.imageid.to_s if image.nil? image_id = image.imageid || nil elsif @machine.provider_config.image distribution_id = nil images = @client.image.list image = images.find { |i| i.label.downcase.include? @machine.provider_config.image.downcase } fail Errors::ImageMatch, image: @machine.provider_config.image.to_s if image.nil? image_id = image.imageid || nil end if @machine.provider_config.kernel kernels = @client.avail.kernels(isxen: nil, iskvm: 1) kernel = kernels.find { |k| k.label.downcase.include? @machine.provider_config.kernel.downcase } raise( Errors::KernelMatch, kernel: @machine.provider_config.kernel.to_s ) if kernel == nil kernel_id = kernel.kernelid || nil else kernel_id = @machine.provider_config.kernelid end if @machine.provider_config.datacenter datacenters = @client.avail.datacenters datacenter = datacenters.find { |d| d.abbr == @machine.provider_config.datacenter } fail Errors::DatacenterMatch, datacenter: @machine.provider_config.datacenter if datacenter.nil? datacenter_id = datacenter.datacenterid else datacenters = @client.avail.datacenters datacenter = datacenters.find { |d| d.datacenterid == @machine.provider_config.datacenterid } fail Errors::DatacenterMatch, datacenter: @machine.provider_config.datacenter if datacenter.nil? datacenter_id = datacenter.datacenterid end if @machine.provider_config.plan plan_label = normalize_plan_label(@machine.provider_config.plan) plans = @client.avail.linodeplans plan = plans.find { |p| p.label.include? plan_label } fail Errors::PlanID, plan: @machine.provider_config.plan if plan.nil? plan_id = plan.planid else plans = @client.avail.linodeplans plan = plans.find { |p| p.planid.to_i == @machine.provider_config.planid.to_i } fail Errors::PlanID, plan: @machine.provider_config.planid if plan.nil? plan_id = @machine.provider_config.planid end ### Disk Images disk_size = plan['disk'].to_i * 1024 xvda_size, swap_size, xvdc_size = @machine.provider_config.xvda_size, @machine.provider_config.swap_size, @machine.provider_config.xvdc_size swap_size = swap_size.to_i xvda_size = xvda_size == true ? disk_size - swap_size : xvda_size.to_i xvdc_size = (xvdc_size.is_a?(Vagrant::Config::V2::DummyConfig) or xvdc_size == true) ? (disk_size - swap_size - xvda_size).abs : xvdc_size.to_i if ( xvda_size + swap_size + xvdc_size) > disk_size fail Errors::DiskSize, current: (xvda_size + swap_size + xvdc_size), max: disk_size end env[:ui].info I18n.t('vagrant_linode.info.creating') # submit new linode request result = @client.linode.create( planid: plan_id, datacenterid: datacenter_id, paymentterm: @machine.provider_config.paymentterm || 1 ) @machine.id = result['linodeid'].to_s env[:ui].info I18n.t('vagrant_linode.info.created', linodeid: @machine.id, label: (@machine.provider_config.label or "linode#{@machine.id}")) # @client.linode.job.list(:linodeid => @machine.id, :pendingonly => 1) # assign the machine id for reference in other commands disklist = [] if stackscript_id disk = @client.linode.disk.createfromstackscript( linodeid: @machine.id, stackscriptid: stackscript_id, stackscriptudfresponses: JSON.dump(stackscript_udf_responses), distributionid: distribution_id, label: 'Vagrant Disk Distribution ' + distribution_id.to_s + ' Linode ' + @machine.id, type: 'ext4', size: xvda_size, rootsshkey: pubkey, rootpass: root_pass ) disklist.push(disk['diskid']) elsif distribution_id disk = @client.linode.disk.createfromdistribution( linodeid: @machine.id, distributionid: distribution_id, label: 'Vagrant Disk Distribution ' + distribution_id.to_s + ' Linode ' + @machine.id, type: 'ext4', size: xvda_size, rootsshkey: pubkey, rootpass: root_pass ) disklist.push(disk['diskid']) elsif image_id disk = @client.linode.disk.createfromimage( linodeid: @machine.id, imageid: image_id, label: 'Vagrant Disk Image (' + image_id.to_s + ') for ' + @machine.id, size: xvda_size, rootsshkey: pubkey, rootpass: root_pass ) disklist.push(disk['diskid']) else disklist.push('') end if swap_size > 0 swap = @client.linode.disk.create( linodeid: @machine.id, label: 'Vagrant swap', type: 'swap', size: swap_size ) disklist.push(swap['diskid']) else disklist.push('') end if xvdc_size > 0 xvdc_type = @machine.provider_config.xvdc_type.is_a?(Vagrant::Config::V2::DummyConfig) ? "raw" : @machine.provider_config.xvdc_type xvdc = @client.linode.disk.create( linodeid: @machine.id, label: 'Vagrant Leftover Disk Linode ' + @machine.id, type: xvdc_type, size: xvdc_size, ) disklist.push(xvdc['diskid']) else disklist.push('') end config = @client.linode.config.create( linodeid: @machine.id, label: 'Vagrant Config', disklist: disklist.join(','), kernelid: kernel_id ) # @todo: allow provisioning to set static configuration for networking if @machine.provider_config.private_networking private_network = @client.linode.ip.addprivate linodeid: @machine.id end label = @machine.provider_config.label label = label || @machine.name if @machine.name != 'default' label = label || get_server_name group = @machine.provider_config.group group = "" if @machine.provider_config.group == false Services::VolumeManager.new(@machine, @client.volume, env[:ui]).perform result = @client.linode.update( linodeid: @machine.id, label: label, lpm_displaygroup: group ) env[:ui].info I18n.t('vagrant_linode.info.booting', linodeid: @machine.id) bootjob = @client.linode.boot linodeid: @machine.id # sleep 1 until ! @client.linode.job.list(:linodeid => @machine.id, :jobid => bootjob['jobid'], :pendingonly => 1).length wait_for_event(env, bootjob['jobid']) # refresh linode state with provider and output ip address linode = Provider.linode(@machine, refresh: true) public_network = linode.network.find { |network| network['ispublic'] == 1 } env[:ui].info I18n.t('vagrant_linode.info.linode_ip', ip: public_network['ipaddress']) if private_network env[:ui].info I18n.t('vagrant_linode.info.linode_private_ip', ip: private_network['ipaddress']) end # wait for ssh to be ready switch_user = @machine.provider_config.setup? user = @machine.config.ssh.username if switch_user @machine.config.ssh.username = 'root' @machine.config.ssh.password = root_pass end retryable(tries: 25, sleep: 10) do # @todo bump tries when this is solid next if env[:interrupted] fail 'not ready' unless @machine.communicate.ready? end @machine.config.ssh.username = user @app.call(env) end # Both the recover and terminate are stolen almost verbatim from # the Vagrant AWS provider up action # def recover(env) # print YAML::dump env['vagrant_error'] # return if env['vagrant.error'].is_a?(Vagrant::Errors::VagrantError) # if @machine.state.id != -1 # terminate(env) # end # end # generate a random name if server name is empty def get_server_name "vagrant_linode-#{rand.to_s.split('.')[1]}" end def terminate(env) destroy_env = env.dup destroy_env.delete(:interrupted) destroy_env[:config_validate] = false destroy_env[:force_confirm_destroy] = true env[:action_runner].run(Actions.destroy, destroy_env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/message_not_off.rb
lib/vagrant-linode/actions/message_not_off.rb
module VagrantPlugins module Linode module Actions class MessageNotOff def initialize(app, env) @app = app end def call(env) env[:ui].info(I18n.t("vagrant_linode.info.not_off")) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/destroy.rb
lib/vagrant-linode/actions/destroy.rb
require 'vagrant-linode/helpers/client' module VagrantPlugins module Linode module Actions class Destroy def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::destroy') end def call(env) @client = env[:linode_api] # submit destroy linode request begin @client.linode.delete(linodeid: @machine.id, skipchecks: true) rescue RuntimeError => e raise unless e.message.include? 'Object not found' end env[:ui].info I18n.t('vagrant_linode.info.destroying') # set the machine id to nil to cleanup local vagrant state @machine.id = nil @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/message_off.rb
lib/vagrant-linode/actions/message_off.rb
module VagrantPlugins module Linode module Actions class MessageOff def initialize(app, env) @app = app end def call(env) env[:ui].info(I18n.t("vagrant_linode.info.off", :status => :off)) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/setup_hostname.rb
lib/vagrant-linode/actions/setup_hostname.rb
# -*- mode: ruby -*- # vi: set ft=ruby : module VagrantPlugins module Linode module Actions class SetupHostname def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::setup_hostname') end def call(env) # Check if setup is enabled return @app.call(env) unless @machine.provider_config.setup? # Set Hostname if @machine.config.vm.hostname env[:ui].info I18n.t('vagrant_linode.info.modifying_host', name: @machine.config.vm.hostname) @machine.communicate.execute(<<-BASH) sudo echo -n #{@machine.config.vm.hostname} > /etc/hostname; sudo hostname -F /etc/hostname BASH end end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/read_ssh_info.rb
lib/vagrant-linode/actions/read_ssh_info.rb
require 'log4r' module VagrantPlugins module Linode module Actions # This action reads the SSH info for the machine and puts it into the # `:machine_ssh_info` key in the environment. class ReadSSHInfo def initialize(app, _env) @env = _env @app = app @machine = _env[:machine] @logger = Log4r::Logger.new('vagrant_linode::action::read_ssh_info') end def call(env) env[:machine_ssh_info] = read_ssh_info(env[:linode_api], @machine) @app.call(env) end def read_ssh_info(_linode, machine) return nil if machine.id.nil? server = Provider.linode(machine, refresh: true) @env[:ui].info "Machine State ID: %s" % [machine.state.id] #return nil if machine.state.id != :active # @todo this seems redundant to the next line. may be more correct. if server.nil? # The machine can't be found @logger.info("Machine couldn't be found, assuming it got destroyed.") machine.id = nil return nil end public_network = server.network.find { |network| network['ispublic'] == 1 } @env[:ui].info "IP Address: %s" % public_network['ipaddress'] { host: public_network['ipaddress'], port: '22', username: 'root', private_key_path: machine.config.ssh.private_key_path } end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/list_distributions.rb
lib/vagrant-linode/actions/list_distributions.rb
module VagrantPlugins module Linode module Actions class ListDistributions def initialize(app, _env) @app = app end def call(env) linode_api = env[:linode_api] env[:ui].info ('%-4s %-6s %s' % ['ID', 'Size', 'Distribution Name']) linode_api.avail.distributions.sort_by(&:distributionid).each do |dist| env[:ui].info ('%-4s %-6s %s' % [dist.distributionid, dist.minimagesize, dist.label]) end @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
displague/vagrant-linode
https://github.com/displague/vagrant-linode/blob/0b06818ea50a408b793d14653d3bc34835b1dac0/lib/vagrant-linode/actions/power_off.rb
lib/vagrant-linode/actions/power_off.rb
require 'vagrant-linode/helpers/client' require 'vagrant-linode/helpers/waiter' # TODO: --force module VagrantPlugins module Linode module Actions class PowerOff include Helpers::Waiter def initialize(app, env) @app = app @machine = env[:machine] @logger = Log4r::Logger.new('vagrant::linode::power_off') end def call(env) @client = env[:linode_api] # submit power off linode request result = @client.linode.shutdown(linodeid: @machine.id) # wait for request to complete env[:ui].info I18n.t('vagrant_linode.info.powering_off') wait_for_event(env, result['jobid']) # refresh linode state with provider Provider.linode(@machine, refresh: true) @app.call(env) end end end end end
ruby
MIT
0b06818ea50a408b793d14653d3bc34835b1dac0
2026-01-04T17:55:46.227254Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/server.rb
server/server.rb
require "./server/init" disable :logging set :root, File.dirname(__FILE__) + "/../" get "/favicon.ico" do "" end get "/*" do send_file "public/index.html" end
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/init.rb
server/init.rb
Dir['./server/isolate*/lib'].each do |dir| $: << dir end require "rubygems" require "isolate/now" require "sinatra"
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/isolate/lib/isolate.rb
server/isolate/lib/isolate.rb
require "isolate/sandbox" # Restricts +GEM_PATH+ and +GEM_HOME+ and provides a DSL for # expressing your code's runtime Gem dependencies. See README.rdoc for # rationale, limitations, and examples. module Isolate # Duh. VERSION = "3.2.2" # Disable Isolate. If a block is provided, isolation will be # disabled for the scope of the block. def self.disable &block sandbox.disable(&block) end # What environment should be isolated? Consults environment # variables <tt>ISOLATE_ENV</tt>, <tt>RAILS_ENV</tt>, and # <tt>RACK_ENV</tt>. Defaults to <tt>"development"</tt> if none are # set. def self.env ENV["ISOLATE_ENV"] || ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" end @@sandbox = nil # A singleton instance of Isolate::Sandbox. def self.sandbox @@sandbox end # Set the singleton. Intended for Hoe::Isolate and other tools that # make their own. def self.sandbox= o @@sandbox = o end # Declare an isolated RubyGems environment, installed in +path+. Any # block given will be <tt>instance_eval</tt>ed, see # Isolate::Sandbox#gem and Isolate::Sandbox#environment for the sort # of stuff you can do. # # Valid options: # # :cleanup:: Should obsolete gems be removed? Default is +true+. # # :file:: Specify an Isolate file to +instance_eval+. Default is # <tt>Isolate</tt> or <tt>config/isolate.rb</tt>, whichever # is found first. Passing <tt>false</tt> disables file # loading. # # :install:: Should missing gems be installed? Default is +true+. # # :multiruby:: Should Isolate assume that multiple Ruby versions # will be used simultaneously? If so, gems will be # segregated by Ruby version. Default is +true+. # # :path:: Where should isolated gems be kept? Default is # <tt>"tmp/isolate"</tt>, and a Ruby version specifier suffix # will be added if <tt>:multiruby</tt> is +true+. # # :system:: Should system gems be allowed to satisfy dependencies? # Default is +true+. # # :verbose:: Should Isolate be chatty during installs and nukes? # Default is +true+. def self.now! options = {}, &block @@sandbox = Isolate::Sandbox.new options, &block @@sandbox.activate end # Poke RubyGems, since we've probably monkeyed with a bunch of paths # and suchlike. Clears paths, loaded specs, and source indexes. def self.refresh # :nodoc: Gem.loaded_specs.clear Gem.clear_paths Gem::Specification.reset end end
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/isolate/lib/isolate/events.rb
server/isolate/lib/isolate/events.rb
module Isolate # A simple way to watch and extend the Isolate lifecycle. # # Isolate::Events.watch Isolate::Sandbox, :initialized do |sandbox| # puts "A sandbox just got initialized: #{sandbox}" # end # # Read the source for Isolate::Sandbox and Isolate::Entry to see # what sort of events are fired. module Events # Watch for an event called +name+ from an instance of # +klass+. +block+ will be called when the event occurs. Block # args vary by event, but usually an instance of the relevant # class is passed. def self.watch klass, name, &block watchers[[klass, name]] << block end def self.fire klass, name, *args #:nodoc: watchers[[klass, name]].each do |block| block[*args] end end def self.watchers #:nodoc: @watchers ||= Hash.new { |h, k| h[k] = [] } end def fire name, after = nil, *args, &block #:nodoc: Isolate::Events.fire self.class, name, self, *args if after && block_given? yield self Isolate::Events.fire self.class, after, *args end end end end
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/isolate/lib/isolate/entry.rb
server/isolate/lib/isolate/entry.rb
require "isolate/events" require "rubygems" require "rubygems/command" require "rubygems/dependency_installer" require "rubygems/requirement" require "rubygems/version" module Isolate # An isolated Gem, with requirement, environment restrictions, and # installation options. Generally intended for internal use. This # class exposes lifecycle events for extension, see Isolate::Events # for more information. class Entry include Events # Which environments does this entry care about? Generally an # Array of Strings. An empty array means "all", not "none". attr_reader :environments # What's the name of this entry? Generally the name of a gem. attr_reader :name # Extra information or hints for installation. See +initialize+ # for well-known keys. attr_reader :options # What version of this entry is required? Expressed as a # Gem::Requirement, which see. attr_reader :requirement # Create a new entry. Takes +sandbox+ (currently an instance of # Isolate::Sandbox), +name+ (as above), and any number of optional # version requirements (generally strings). Options can be passed # as a trailing hash. Well-known keys: # # :args:: Command-line build arguments. Passed to the gem at # installation time. # # :source:: An alternative RubyGems source for this gem. def initialize sandbox, name, *requirements @environments = [] @file = nil @name = name @options = {} @requirement = Gem::Requirement.default @sandbox = sandbox if /\.gem$/ =~ @name && File.file?(@name) @file = File.expand_path @name @name = File.basename(@file, ".gem"). gsub(/-#{Gem::Version::VERSION_PATTERN}$/, "") end update(*requirements) end # Activate this entry. Fires <tt>:activating</tt> and # <tt>:activated</tt>. def activate fire :activating, :activated do spec = self.specification raise Gem::LoadError, "Couldn't resolve: #{self}" unless spec spec.activate end end # Install this entry in the sandbox. Fires <tt>:installing</tt> # and <tt>:installed</tt>. def install old = Gem.sources.dup begin fire :installing, :installed do installer = Gem::DependencyInstaller.new(:development => false, :generate_rdoc => false, :generate_ri => false, :install_dir => @sandbox.path) Gem::Command.build_args = Array(options[:args]) if options[:args] Gem.sources += Array(options[:source]) if options[:source] installer.install @file || name, requirement end ensure Gem.sources = old Gem::Command.build_args = nil end end # Is this entry interested in +environment+? def matches? environment environments.empty? || environments.include?(environment) end # Is this entry satisfied by +spec+ (generally a # Gem::Specification)? def matches_spec? spec name == spec.name and requirement.satisfied_by? spec.version end # The Gem::Specification for this entry or nil if it isn't resolveable. def specification Gem::Specification.find_by_name(name, requirement) rescue Gem::LoadError nil end # Updates this entry's environments, options, and # requirement. Environments and options are merged, requirement is # replaced. Fires <tt>:updating</tt> and <tt>:updated</tt>. def update *reqs fire :updating, :updated do @environments |= @sandbox.environments @options.merge! reqs.pop if Hash === reqs.last @requirement = Gem::Requirement.new reqs unless reqs.empty? end self end def to_s "Entry[#{name.inspect}, #{requirement.to_s.inspect}]" end alias :inspect :to_s end end
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/isolate/lib/isolate/sandbox.rb
server/isolate/lib/isolate/sandbox.rb
require "fileutils" require "isolate/entry" require "isolate/events" require "rbconfig" require "rubygems/defaults" require "rubygems/uninstaller" require "rubygems/deprecate" module Isolate # An isolated environment. This class exposes lifecycle events for # extension, see Isolate::Events for more information. class Sandbox include Events DEFAULT_PATH = "tmp/isolate" # :nodoc: attr_reader :entries # :nodoc: attr_reader :environments # :nodoc: attr_reader :files # :nodoc: # Create a new Isolate::Sandbox instance. See Isolate.now! for the # most common use of the API. You probably don't want to use this # constructor directly. Fires <tt>:initializing</tt> and # <tt>:initialized</tt>. def initialize options = {}, &block @enabled = false @entries = [] @environments = [] @files = [] @options = options fire :initializing user = File.expand_path "~/.isolate/user.rb" load user if File.exist? user file, local = nil unless FalseClass === options[:file] file = options[:file] || Dir["{Isolate,config/isolate.rb}"].first local = "#{file}.local" if file end load file if file if block_given? /\@(.+?):\d+/ =~ block.to_s files << ($1 || "inline block") instance_eval(&block) end load local if local && File.exist?(local) fire :initialized end # Activate this set of isolated entries, respecting an optional # +environment+. Points RubyGems to a separate repository, messes # with paths, auto-installs gems (if necessary), activates # everything, and removes any superfluous gem (again, if # necessary). If +environment+ isn't specified, +ISOLATE_ENV+, # +RAILS_ENV+, and +RACK_ENV+ are checked before falling back to # <tt>"development"</tt>. Fires <tt>:activating</tt> and # <tt>:activated</tt>. def activate environment = nil enable unless enabled? fire :activating env = (environment || Isolate.env).to_s install env if install? entries.each do |e| e.activate if e.matches? env end cleanup if cleanup? fire :activated self end def cleanup # :nodoc: fire :cleaning gem_dir = Gem.dir global, local = Gem::Specification.partition { |s| s.base_dir != gem_dir } legit = legitimize! extra = (local - legit) + (local & global) self.remove(*extra) fire :cleaned end def cleanup? install? and @options.fetch(:cleanup, true) end def disable &block return self if not enabled? fire :disabling ENV.replace @old_env $LOAD_PATH.replace @old_load_path @enabled = false Isolate.refresh fire :disabled begin; return yield ensure enable end if block_given? self end def enable # :nodoc: return self if enabled? fire :enabling @old_env = ENV.to_hash @old_load_path = $LOAD_PATH.dup path = self.path FileUtils.mkdir_p path ENV["GEM_HOME"] = path unless system? isolate_lib = File.expand_path "../..", __FILE__ # manually deactivate pre-isolate gems... is this just for 1.9.1? $LOAD_PATH.reject! do |p| p != isolate_lib && Gem.path.any? { |gp| p.include?(gp) } end # HACK: Gotta keep isolate explicitly in the LOAD_PATH in # subshells, and the only way I can think of to do that is by # abusing RUBYOPT. unless ENV["RUBYOPT"] =~ /\s+-I\s*#{Regexp.escape isolate_lib}\b/ ENV["RUBYOPT"] = "#{ENV['RUBYOPT']} -I#{isolate_lib}" end ENV["GEM_PATH"] = path end bin = File.join path, "bin" unless ENV["PATH"].split(File::PATH_SEPARATOR).include? bin ENV["PATH"] = [bin, ENV["PATH"]].join File::PATH_SEPARATOR end ENV["ISOLATED"] = path if system? then Gem.path.unshift path # HACK: this is just wrong! Gem.path.uniq! # HACK: needed for the previous line :( end Isolate.refresh @enabled = true fire :enabled self end def enabled? @enabled end # Restricts +gem+ calls inside +block+ to a set of +environments+. def environment *environments, &block old = @environments @environments = @environments.dup.concat environments.map { |e| e.to_s } instance_eval(&block) ensure @environments = old end alias_method :env, :environment # Express a gem dependency. Works pretty much like RubyGems' +gem+ # method, but respects +environment+ and doesn't activate 'til # later. def gem name, *requirements entry = entries.find { |e| e.name == name } return entry.update(*requirements) if entry entries << entry = Entry.new(self, name, *requirements) entry end # A source index representing only isolated gems. def index @index ||= Gem::SourceIndex.from_gems_in File.join(path, "specifications") end def install environment # :nodoc: fire :installing installable = entries.select do |e| !e.specification && e.matches?(environment) end unless installable.empty? padding = Math.log10(installable.size).to_i + 1 format = "[%0#{padding}d/%s] Isolating %s (%s)." installable.each_with_index do |entry, i| log format % [i + 1, installable.size, entry.name, entry.requirement] entry.install end Gem::Specification.reset end fire :installed self end def install? # :nodoc: @options.fetch :install, true end def load file # :nodoc: files << file instance_eval IO.read(file), file, 1 end def log s # :nodoc: $stderr.puts s if verbose? end def multiruby? @options.fetch :multiruby, true end def options options = nil @options.merge! options if options @options end def path base = @options.fetch :path, DEFAULT_PATH unless @options.key?(:multiruby) && @options[:multiruby] == false suffix = "#{Gem.ruby_engine}-#{RbConfig::CONFIG['ruby_version']}" base = File.join(base, suffix) unless base =~ /#{suffix}/ end File.expand_path base end def remove(*extra) unless extra.empty? padding = Math.log10(extra.size).to_i + 1 format = "[%0#{padding}d/%s] Nuking %s." extra.each_with_index do |e, i| log format % [i + 1, extra.size, e.full_name] Gem::DefaultUserInteraction.use_ui Gem::SilentUI.new do uninstaller = Gem::Uninstaller.new(e.name, :version => e.version, :ignore => true, :executables => true, :install_dir => e.base_dir) uninstaller.uninstall end end end end def system? @options.fetch :system, true end def verbose? @options.fetch :verbose, true end private # Returns a list of Gem::Specification instances that 1. exist in # the isolated gem path, and 2. are allowed to be there. Used in # cleanup. It's only an external method 'cause recursion is # easier. def legitimize! deps = entries specs = [] deps.flatten.each do |dep| spec = case dep when Gem::Dependency then begin dep.to_spec rescue Gem::LoadError nil end when Isolate::Entry then dep.specification else raise "unknown dep: #{dep.inspect}" end if spec then specs.concat legitimize!(spec.runtime_dependencies) specs << spec end end specs.uniq end dep_module = defined?(Gem::Deprecate) ? Gem::Deprecate : Deprecate extend dep_module deprecate :index, :none, 2011, 11 end end
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/isolate/lib/isolate/now.rb
server/isolate/lib/isolate/now.rb
require "isolate" require "isolate/rake" if defined?(Rake) Isolate.now!
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
mihar/backbone-skeleton
https://github.com/mihar/backbone-skeleton/blob/d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7/server/isolate/lib/isolate/rake.rb
server/isolate/lib/isolate/rake.rb
require "isolate" namespace :isolate do desc "Show current isolated environment." task :env do require "pathname" sandbox = Isolate.sandbox here = Pathname Dir.pwd path = Pathname(sandbox.path).relative_path_from here files = sandbox.files.map { |f| Pathname(f) } puts puts " path: #{path}" puts " env: #{Isolate.env}" files.map! { |f| f.absolute? ? f.relative_path_from(here) : f } puts " files: #{files.join ', '}" puts %w(cleanup? enabled? install? multiruby? system? verbose?).each do |flag| printf "%10s %s\n", flag, sandbox.send(flag) end grouped = Hash.new { |h, k| h[k] = [] } sandbox.entries.each { |e| grouped[e.environments] << e } puts grouped.keys.sort.each do |envs| title = "all environments" if envs.empty? title ||= envs.join ", " puts "[#{title}]" grouped[envs].each do |e| gem = "gem #{e.name}, #{e.requirement}" gem << ", #{e.options.inspect}" unless e.options.empty? puts gem end puts end end desc "Run an isolated command or subshell." task :sh, [:command] do |t, args| exec args.command || ENV["SHELL"] || ENV["COMSPEC"] end desc "Which isolated gems have updates available?" task :stale do outdated = [] sandbox = Isolate.sandbox outdated = sandbox.entries.reject { |entry| entry.specification } Gem::Specification.outdated.each do |name| entry = sandbox.entries.find { |e| e.name == name } next unless entry outdated << entry end outdated.sort_by { |e| e.name }.each do |entry| local = entry.specification ? entry.specification.version : "0" dep = Gem::Dependency.new entry.name, ">= #{local}" remotes = Gem::SpecFetcher.fetcher.fetch dep remote = remotes.last.first.version puts "#{entry.name} (#{local} < #{remote})" end end desc "Removes gems that have updates available" task :freshen do outdated = [] sandbox = Isolate.sandbox extra = sandbox.entries.reject { |entry| entry.specification } Gem::Specification.outdated.each do |name| entry = sandbox.entries.find { |e| e.name == name } next unless entry extra << entry.specification end sandbox.remove(*extra) end end
ruby
MIT
d72c3f5110092d8b0bd2b0be1a3848fd9d8b61e7
2026-01-04T17:55:51.535665Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/integration/default/serverspec/default_spec.rb
test/integration/default/serverspec/default_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'net/http' require 'serverspec' set :backend, :exec describe 'rackup' do context '/opt/rack1' do describe port(8000) do it { is_expected.to be_listening } end describe 'HTTP response' do subject { Net::HTTP.new('localhost', 8000).get('/').body } it { is_expected.to eq 'Hello world' } end end # /context /opt/rack1 context '/opt/rack2' do describe port(8001) do it { is_expected.to be_listening } end describe 'HTTP response' do subject { Net::HTTP.new('localhost', 8001).get('/').body } it { is_expected.to start_with '/opt/rack2' } end end # /context /opt/rack2 end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/integration/default/serverspec/rails_spec.rb
test/integration/default/serverspec/rails_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'net/http' require 'serverspec' set :backend, :exec describe 'rails', if: File.exists?('/opt/test_rails') do describe port(9001) do it { is_expected.to be_listening } end let(:http) { Net::HTTP.new('localhost', 9001) } describe '/' do subject { http.get('/') } its(:code) { is_expected.to eq '200' } its(:body) { is_expected.to include '<h1>Hello, Rails!</h1>' } end describe '/articles' do subject { http.get('/articles') } its(:code) { is_expected.to eq '200' } its(:body) { is_expected.to include '<h1>Listing articles</h1>' } end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/integration/default/serverspec/sinatra_spec.rb
test/integration/default/serverspec/sinatra_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'net/http' require 'serverspec' set :backend, :exec describe 'sinatra' do describe port(9000) do it { is_expected.to be_listening } end let(:http) { Net::HTTP.new('localhost', 9000) } describe '/' do subject { http.get('/') } its(:code) { is_expected.to eq '404' } end describe '/hi' do subject { http.get('/hi') } its(:code) { is_expected.to eq '200' } its(:body) { is_expected.to eq 'Hello World!' } end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/cookbook/metadata.rb
test/cookbook/metadata.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name 'application_ruby_test' depends 'application_git' depends 'application_ruby' depends 'poise-build-essential'
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/cookbook/recipes/sinatra.rb
test/cookbook/recipes/sinatra.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe 'poise-build-essential' package value_for_platform_family(debian: 'ruby-dev', rhel: 'ruby-devel') application '/opt/test_sinatra' do git 'https://github.com/poise/test_sinatra.git' bundle_install do deployment true end unicorn do port 9000 end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/cookbook/recipes/rails.rb
test/cookbook/recipes/rails.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # RHEL 6 is too old to run Rails 4.2 on the system Ruby. return if platform_family?('rhel') && node['platform_version'].start_with?('6') include_recipe 'poise-build-essential' package value_for_platform_family(debian: 'ruby-dev', rhel: 'ruby-devel') package value_for_platform_family(debian: 'zlib1g-dev', rhel: 'zlib-devel') package value_for_platform_family(debian: 'libsqlite3-dev', rhel: 'sqlite-devel') package 'tar' if platform_family?('rhel') application '/opt/test_rails' do git 'https://github.com/poise/test_rails.git' bundle_install do deployment true without %w{development test} end rails do database 'sqlite3:///db.sqlite3' migrate true secret_token 'd78fe08df56c9' end unicorn do port 9001 end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/cookbook/recipes/default.rb
test/cookbook/recipes/default.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # For netstat in serverspec. package 'net-tools' ruby_runtime 'any' do provider :system version '' end ruby_gem 'rack' do # Rack 1.6.2-1.6.4 broke 1.8 compat. version '1.6.1' end application '/opt/rack1' do file '/opt/rack1/config.ru' do content <<-EOH use Rack::ContentLength run proc {|env| [200, {'Content-Type' => 'text/plain'}, ['Hello world']] } EOH end rackup do port 8000 end end application '/opt/rack2' do file '/opt/rack2/Gemfile' do content <<-EOH source 'https://rubygems.org/' # See above ruby_gem[rack] for matching version. gem 'rack', '1.6.1' EOH end file '/opt/rack2/config.ru' do content <<-EOH use Rack::ContentLength run proc {|env| [200, {'Content-Type' => 'text/plain'}, [caller.first]] } EOH end bundle_install do vendor true end rackup do port 8001 end end include_recipe '::rails' include_recipe '::sinatra'
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/cookbook/attributes/default.rb
test/cookbook/attributes/default.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # override['poise-service']['provider'] = 'dummy'
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/spec/spec_helper.rb
test/spec/spec_helper.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_boiler/spec_helper' require 'poise_application_ruby' require 'poise_application/cheftie' require 'poise_ruby/cheftie'
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/spec/resources/ruby_spec.rb
test/spec/resources/ruby_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoiseApplicationRuby::Resources::Ruby do recipe do application '/test' do ruby do provider :dummy end ruby_gem 'test' end end it { is_expected.to install_application_ruby('/test').with(ruby_binary: '/ruby', gem_binary: '/gem') } it { is_expected.to install_application_ruby_gem('test').with(ruby: '/ruby', gem_binary: '/gem') } end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/test/spec/resources/ruby_execute_spec.rb
test/spec/resources/ruby_execute_spec.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe PoiseApplicationRuby::Resources::RubyExecute do step_into(:application_ruby_execute) recipe do application '/srv/myapp' do owner 'myuser' group 'mygroup' environment ENVKEY: 'ENVVALUE' ruby('') { provider :dummy } ruby_execute 'myapp.rb' end end it do # Check which method to stub. I'm not super proud of this code, sorry. method_to_stub = if IO.read(described_class::Provider.instance_method(:action_run).source_location.first) =~ /shell_out_with_systems_locale/ :shell_out_with_systems_locale! else :shell_out! end expect_any_instance_of(described_class::Provider).to receive(method_to_stub).with( '/ruby myapp.rb', user: 'myuser', group: 'mygroup', cwd: '/srv/myapp', timeout: 3600, returns: 0, environment: {'ENVKEY' => 'ENVVALUE'}, log_level: :info, log_tag: 'application_ruby_execute[myapp.rb]', ) is_expected.to run_application_ruby_execute('myapp.rb').with(user: 'myuser', group: 'mygroup', cwd: '/srv/myapp') end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby.rb
lib/poise_application_ruby.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module PoiseApplicationRuby autoload :AppMixin, 'poise_application_ruby/app_mixin' autoload :Error, 'poise_application_ruby/error' autoload :Resources, 'poise_application_ruby/resources' autoload :ServiceMixin, 'poise_application_ruby/service_mixin' autoload :VERSION, 'poise_application_ruby/version' end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/app_mixin.rb
lib/poise_application_ruby/app_mixin.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise/backports' require 'poise/utils' require 'poise_application/app_mixin' require 'poise_ruby/ruby_command_mixin' module PoiseApplicationRuby # A helper mixin for Ruby application resources and providers. # # @since 4.0.0 module AppMixin include Poise::Utils::ResourceProviderMixin # A helper mixin for Ruby application resources. module Resource include PoiseApplication::AppMixin::Resource include PoiseRuby::RubyCommandMixin::Resource # @!attribute parent_ruby # Override the #parent_ruby from RubyCommandMixin to grok the # application level parent as a default value. # @return [PoiseRuby::Resources::RubyRuntime::Resource, nil] parent_attribute(:ruby, type: :ruby_runtime, optional: true, default: lazy { app_state_ruby.equal?(self) ? nil : app_state_ruby }) # @!attribute parent_bundle # Parent bundle install context. # @return [PoiseRuby::Resources::BundleInstall::Resource, nil] parent_attribute(:bundle, type: :ruby_runtime, optional: true, auto: false, default: lazy { app_state_bundle.equal?(self) ? nil : app_state_bundle }) # @attribute app_state_ruby # The application-level Ruby parent. # @return [PoiseRuby::Resources::RubyRuntime::Resource, nil] def app_state_ruby(ruby=Poise::NOT_PASSED) unless ruby == Poise::NOT_PASSED app_state[:ruby] = ruby end app_state[:ruby] end # @attribute app_state_bundle # The application-level Bundle parent. # @return [PoiseRuby::Resources::BundleInstall::Resource, nil] def app_state_bundle(bundle=Poise::NOT_PASSED) unless bundle == Poise::NOT_PASSED app_state[:bundle] = bundle end app_state[:bundle] end # A merged hash of environment variables for both the application state # and parent ruby. # # @return [Hash<String, String>] def app_state_environment_ruby env = app_state_environment env = env.merge(parent_ruby.ruby_environment) if parent_ruby env['BUNDLE_GEMFILE'] = parent_bundle.gemfile_path if parent_bundle env end # Update ruby_from_parent to transfer {#parent_bundle} too. # # @param resource [Chef::Resource] Resource to inherit from. # @return [void] def ruby_from_parent(resource) super parent_bundle(resource.parent_bundle) if resource.parent_bundle end end # A helper mixin for Ruby application providers. module Provider include PoiseApplication::AppMixin::Provider end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/version.rb
lib/poise_application_ruby/version.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module PoiseApplicationRuby VERSION = '4.1.1.pre' end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources.rb
lib/poise_application_ruby/resources.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_application_ruby/resources/bundle_install' require 'poise_application_ruby/resources/puma' require 'poise_application_ruby/resources/rackup' require 'poise_application_ruby/resources/rails' require 'poise_application_ruby/resources/ruby' require 'poise_application_ruby/resources/ruby_execute' require 'poise_application_ruby/resources/ruby_gem' require 'poise_application_ruby/resources/thin' require 'poise_application_ruby/resources/unicorn'
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/service_mixin.rb
lib/poise_application_ruby/service_mixin.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise/utils' require 'poise_application/service_mixin' require 'poise_languages/utils' require 'poise_ruby/bundler_mixin' require 'poise_application_ruby/app_mixin' module PoiseApplicationRuby # A helper mixin for Ruby service resources and providers. # # @since 4.0.0 module ServiceMixin include Poise::Utils::ResourceProviderMixin # A helper mixin for Ruby service resources. module Resource include PoiseApplication::ServiceMixin::Resource include PoiseApplicationRuby::AppMixin::Resource end # A helper mixin for Ruby service providers. module Provider include PoiseApplication::ServiceMixin::Provider include PoiseApplicationRuby::AppMixin::Provider include PoiseRuby::RubyCommandMixin::Provider include PoiseRuby::BundlerMixin # Set up the service for running Ruby stuff. def service_options(resource) super # Closure scoping for #ruby_command below. self_ = self # Create a new singleton method that fills in Python for you. resource.define_singleton_method(:ruby_command) do |val| path = self_.new_resource.app_state_environment_ruby['PATH'] || ENV['PATH'] cmd = if self_.new_resource.parent_bundle bundle_exec_command(val, path: path) else # Insert the gem executable directory at the front of the path. gem_environment = self_.send(:ruby_shell_out!, self_.new_resource.gem_binary, 'environment') matches = gem_environment.stdout.scan(/EXECUTABLE DIRECTORY: (.*)$/).first if matches Chef::Log.debug("[#{new_resource}] Prepending gem executable directory #{matches.first} to existing $PATH (#{path})") path = "#{matches.first}:#{path}" end "#{self_.new_resource.ruby} #{PoiseLanguages::Utils.absolute_command(val, path: path)}" end resource.command(cmd) end # Include env vars as needed. resource.environment.update(new_resource.parent_ruby.ruby_environment) if new_resource.parent_ruby resource.environment['BUNDLE_GEMFILE'] = new_resource.parent_bundle.gemfile_path if new_resource.parent_bundle end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/cheftie.rb
lib/poise_application_ruby/cheftie.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_application_ruby/resources'
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/error.rb
lib/poise_application_ruby/error.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_application/error' module PoiseApplicationRuby # Base exception class for poise-application-ruby errors. # # @since 4.0.0 class Error < PoiseApplication::Error end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/rackup.rb
lib/poise_application_ruby/resources/rackup.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider' require 'chef/resource' require 'poise_application_ruby/service_mixin' module PoiseApplicationRuby module Resources # (see Rackup::Resource) # @since 4.0.0 module Rackup class Resource < Chef::Resource include PoiseApplicationRuby::ServiceMixin provides(:application_rackup) # @!attribute port # TCP port to listen on. Defaults to 80. # @return [String, Integer] attribute(:port, kind_of: [String, Integer], default: 80) end class Provider < Chef::Provider include PoiseApplicationRuby::ServiceMixin provides(:application_rackup) private # Find the path to the config.ru. If the resource path was to a # directory, apparent /config.ru. # # @return [String] def configru_path @configru_path ||= if ::File.directory?(new_resource.path) ::File.join(new_resource.path, 'config.ru') else new_resource.path end end # Set up service options for rackup. # # @param resource [PoiseService::Resource] Service resource. # @return [void] def service_options(resource) super resource.ruby_command("rackup --port #{new_resource.port}") resource.directory(::File.dirname(configru_path)) # Older versions of rackup ignore all signals. resource.stop_signal('KILL') end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/rails.rb
lib/poise_application_ruby/resources/rails.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider' require 'chef/resource' require 'poise_application_ruby/app_mixin' require 'poise_application_ruby/error' module PoiseApplicationRuby module Resources # (see Rails::Resource) module Rails # An `application_rails` resource to configure Ruby on Rails applications. # # @since 4.0.0 # @provides application_rails # @action deploy # @example # application '/srv/myapp' do # git '...' # bundle_install # rails do # database do # host node['rails_host'] # end # end # unicorn do # port 8080 # end # end class Resource < Chef::Resource include PoiseApplicationRuby::AppMixin provides(:application_rails) actions(:deploy) # @!attribute app_module # Top-level application module. Only needed for the :initializer style # of secret token configuration, and generally auto-detected. # @return [String, false, nil] attribute(:app_module, kind_of: [String, FalseClass, NilClass], default: lazy { default_app_module }) # @!attribute database # Option collector attribute for Rails database configuration. # @return [Hash] # @example Setting via block # database do # adapter 'postgresql' # database 'blog' # end # @example Setting via URL # database 'postgresql://localhost/blog' attribute(:database, option_collector: true, parser: :parse_database_url) # @!attribute database_config # Template content attribute for the contents of database.yml. # @todo Redo this doc to cover the actual attributes created. # @return [Poise::Helpers::TemplateContent] attribute(:database_config, template: true, default_source: 'database.yml.erb', default_options: lazy { default_database_options }) # @!attribute migrate # Run database migrations. This is a bad idea for real apps. Please # do not use it. # @return [Boolean] attribute(:migrate, equal_to: [true, false], default: false) # @!attribute precompile_assets # Set to true to run rake assets:precompile. By default will try to # auto-detect if Sprockets is in use by looking at config/initializers. # @see #default_precompile_assets # @return [Boolean] attribute(:precompile_assets, equal_to: [true, false], default: lazy { default_precompile_assets }) # @!attribute rails_env # Rails environment name. Defaults to the Chef environment name or # `production` if none is set. # @see #default_rails_env # @return [String] attribute(:rails_env, kind_of: String, default: lazy { default_rails_env }) # @!attribute secret_token # Secret token for Rails session verification and other purposes. On # Rails 4.2 this will be used for secret_key_base. If not set, no # secrets configuration is written. # @return [String, false, nil] attribute(:secret_token, kind_of: [String, FalseClass, NilClass]) # @!attribute secrets_config # Template content attribute for the contents of secrets.yml. Only # used when secrets_mode is :yaml. # @todo Redo this doc to cover the actual attributes created. # @return [Poise::Helpers::TemplateContent] attribute(:secrets_config, template: true, default_source: 'secrets.yml.erb', default_options: lazy { default_secrets_options }) # @!attribute secrets_initializer # Template content attribute for the contents of secret_token.rb. Only # used when secrets_mode is :initializer. # @todo Redo this doc to cover the actual attributes created. # @return [Poise::Helpers::TemplateContent] attribute(:secrets_initializer, template: true, default_source: 'secret_token.rb.erb', default_options: lazy { default_secrets_options }) # @!attribute secrets_mode # Secrets configuration mode. Set to `:yaml` to generate a Rails 4.2 # secrets.yml. Set to `:initializer` to update # `config/initializers/secret_token.rb`. If unspecified this is # auto-detected based on what files exist. # @return [Symbol] attribute(:secrets_mode, equal_to: [:yaml, :initializer], default: lazy { default_secrets_mode }) private # Check if we should run the precompile by default. Looks for the # assets initializer because that is not present with --skip-sprockets. # # @return [Boolean] def default_precompile_assets ::File.exists?(::File.join(path, 'config', 'initializers', 'assets.rb')) end # Check the default environment name. # # @return [String] def default_rails_env node.chef_environment == '_default' ? 'production' : node.chef_environment end # Format a single URL for the database.yml # # @return [Hash] def parse_database_url(url) {'url' => url} end # Default template variables for the database.yml. # # @return [Hash<Symbol, Object>] def default_database_options db_config = {'encoding' => 'utf8', 'reconnect' => true, 'pool' => 5}.merge(database) { config: { rails_env => db_config }, } end # Check which secrets configuration mode is in use based on files. # # @return [Symbol] def default_secrets_mode ::File.exists?(::File.join(path, 'config', 'initializers', 'secret_token.rb')) ? :initializer : :yaml end # Default template variables for the secrets.yml and secret_token.rb. # # @return [Hash<Symbol, Object>] def default_secrets_options { yaml_config: { rails_env => { 'secret_key_base' => secret_token, } }, secret_token: secret_token, app_module: if secrets_mode == :initializer raise Error.new("Unable to extract app module for #{self}, please set app_module property") if !app_module || app_module.empty? app_module end } end # Default application module name. # # @return [String] def default_app_module IO.read(::File.join(path, 'config', 'initializers', 'secret_token.rb'))[/(\w+)::Application\.config\.secret_token/, 1] end end # Provider for `application_rails`. # # @since 4.0.0 # @see Resource # @provides application_rails class Provider < Chef::Provider include PoiseApplicationRuby::AppMixin provides(:application_rails) # `deploy` action for `application_rails`. Ensure all configuration # files are created and other deploy tasks resolved. # # @return [void] def action_deploy set_state notifying_block do write_database_yml unless new_resource.database.empty? write_secrets_config if new_resource.secret_token precompile_assets if new_resource.precompile_assets run_migrations if new_resource.migrate end end private # Set app_state variables for future services et al. def set_state new_resource.app_state_environment[:RAILS_ENV] = new_resource.rails_env new_resource.app_state_environment[:DATABASE_URL] = new_resource.database['url'] if new_resource.database['url'] end # Create a database.yml config file. def write_database_yml file ::File.join(new_resource.path, 'config', 'database.yml') do user new_resource.parent.owner group new_resource.parent.group mode '640' content new_resource.database_config_content sensitive true end end # Dispatch to the correct config writer based on the mode. def write_secrets_config case new_resource.secrets_mode when :yaml write_secrets_yml when :initializer write_secrets_initializer else raise Error.new("Unknown secrets mode #{new_resource.secrets_mode.inspect}") end end # Write a Rails 4.2-style secrets.yml. def write_secrets_yml file ::File.join(new_resource.path, 'config', 'secrets.yml') do user new_resource.parent.owner group new_resource.parent.group mode '640' content new_resource.secrets_config_content sensitive true end end # In-place update a config/initializers/secret_token.rb file. def write_secrets_initializer file ::File.join(new_resource.path, 'config', 'initializers', 'secret_token.rb') do user new_resource.parent.owner group new_resource.parent.group mode '640' content new_resource.secrets_initializer_content sensitive true end end # Precompile assets using the rake task. def precompile_assets # Currently this will always run so the resource will always update :-/ # Better fix would be to shell_out! and parse the output? ruby_execute 'rake assets:precompile' do command %w{rake assets:precompile} user new_resource.parent.owner group new_resource.parent.group cwd new_resource.parent.path environment new_resource.app_state_environment ruby_from_parent new_resource parent_bundle new_resource.parent_bundle if new_resource.parent_bundle end end # Run database migrations using the rake task. def run_migrations # Currently this will always run so the resource will always update :-/ # Better fix would be to shell_out! and parse the output? ruby_execute 'rake db:migrate' do command %w{rake db:migrate} user new_resource.parent.owner group new_resource.parent.group cwd new_resource.parent.path environment new_resource.app_state_environment ruby_from_parent new_resource parent_bundle new_resource.parent_bundle if new_resource.parent_bundle end end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/thin.rb
lib/poise_application_ruby/resources/thin.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider' require 'chef/resource' require 'poise_application_ruby/service_mixin' module PoiseApplicationRuby module Resources # (see Thin::Resource) # @since 4.0.0 module Thin class Resource < Chef::Resource include PoiseApplicationRuby::ServiceMixin provides(:application_thin) attribute(:port, kind_of: [String, Integer], default: 80) attribute(:config_path, kind_of: String) end class Provider < Chef::Provider include PoiseApplicationRuby::ServiceMixin provides(:application_thin) private # Find the path to the config.ru. If the resource path was to a # directory, apparent /config.ru. # # @return [String] def configru_path @configru_path ||= if ::File.directory?(new_resource.path) ::File.join(new_resource.path, 'config.ru') else new_resource.path end end # (see PoiseApplication::ServiceMixin#service_options) def service_options(resource) super cmd = "thin --rackup #{configru_path} --port #{new_resource.port}" cmd << " --config #{::File.expand_path(new_resource.config_path, new_resource.path)}" if new_resource.config_path resource.ruby_command(cmd) end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/ruby_gem.rb
lib/poise_application_ruby/resources/ruby_gem.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_ruby/resources/ruby_gem' require 'poise_application_ruby/app_mixin' module PoiseApplicationRuby module Resources # (see RubyGem::Resource) # @since 4.0.0 module RubyGem # An `application_ruby_gem` resource to install Ruby gems inside an # Application cookbook deployment. # # @provides application_ruby_gem # @action install # @action upgrade # @action remove # @example # application '/srv/myapp' do # ruby_gem 'rack' # end class Resource < PoiseRuby::Resources::RubyGem::Resource include PoiseApplicationRuby::AppMixin provides(:application_ruby_gem) subclass_providers! end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/puma.rb
lib/poise_application_ruby/resources/puma.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider' require 'chef/resource' require 'poise_application_ruby/service_mixin' module PoiseApplicationRuby module Resources # (see Puma::Resource) # @since 4.1.0 module Puma # An `application_puma` resource to manage a puma web application # server. # # @since 4.1.0 # @provides application_puma # @action enable # @action disable # @action start # @action stop # @action restart # @action reload # @example # application '/srv/myapp' do # git '...' # bundle_install # puma do # port 8080 # end # end class Resource < Chef::Resource include PoiseApplicationRuby::ServiceMixin provides(:application_puma) # @!attribute port # Port to bind to. attribute(:port, kind_of: [String, Integer], default: 80) end # Provider for `application_puma`. # # @since 4.1.0 # @see Resource # @provides application_puma class Provider < Chef::Provider include PoiseApplicationRuby::ServiceMixin provides(:application_puma) private # Find the path to the config.ru. If the resource path was to a # directory, apparent /config.ru. # # @return [String] def configru_path @configru_path ||= if ::File.directory?(new_resource.path) ::File.join(new_resource.path, 'config.ru') else new_resource.path end end # Set service resource options. def service_options(resource) super resource.ruby_command("puma --port #{new_resource.port} #{configru_path}") end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/bundle_install.rb
lib/poise_application_ruby/resources/bundle_install.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_ruby/resources/bundle_install' require 'poise_application_ruby/app_mixin' module PoiseApplicationRuby module Resources # (see BundleInstall::Resource) # @since 4.0.0 module BundleInstall # An `application_bundle_install` resource to install a # [Bundler](http://bundler.io/) Gemfile in a web application. # # @note # This resource is not idempotent itself, it will always run `bundle # install`. # @example # application '/srv/my_app' do # bundle_install # end class Resource < PoiseRuby::Resources::BundleInstall::Resource include PoiseApplicationRuby::AppMixin provides(:application_bundle_install) subclass_providers! # Set this resource as the app_state's parent bundle. # # @api private def after_created super.tap do |val| app_state_bundle(self) end end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/ruby_execute.rb
lib/poise_application_ruby/resources/ruby_execute.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_ruby/resources/ruby_execute' require 'poise_application_ruby/app_mixin' module PoiseApplicationRuby module Resources # (see RubyExecute::Resource) # @since 4.0.0 module RubyExecute # An `application_ruby_execute` resource to run Ruby commands inside an # Application cookbook deployment. # # @provides application_ruby_execute # @action run # @example # application '/srv/myapp' do # ruby_execute 'rake build' # end class Resource < PoiseRuby::Resources::RubyExecute::Resource include PoiseApplicationRuby::AppMixin provides(:application_ruby_execute) def initialize(*args) super # Clear some instance variables so my defaults work. remove_instance_variable(:@cwd) remove_instance_variable(:@group) remove_instance_variable(:@user) end # #!attribute cwd # Override the default directory to be the app path if unspecified. # @return [String] attribute(:cwd, kind_of: [String, NilClass, FalseClass], default: lazy { parent && parent.path }) # #!attribute group # Override the default group to be the app group if unspecified. # @return [String, Integer] attribute(:group, kind_of: [String, Integer, NilClass, FalseClass], default: lazy { parent && parent.group }) # #!attribute user # Override the default user to be the app owner if unspecified. # @return [String, Integer] attribute(:user, kind_of: [String, Integer, NilClass, FalseClass], default: lazy { parent && parent.owner }) end # The default provider for `application_ruby_execute`. # # @see Resource # @provides application_ruby_execute class Provider < PoiseRuby::Resources::RubyExecute::Provider provides(:application_ruby_execute) private # Override environment to add the application envivonrment instead. # # @return [Hash] def environment super.tap do |environment| # Don't use the app_state_environment_ruby because we already have # those values in place. environment.update(new_resource.app_state_environment) # Re-apply the resource environment for correct ordering. environment.update(new_resource.environment) if new_resource.environment end end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/ruby.rb
lib/poise_application_ruby/resources/ruby.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_ruby/resources/ruby_runtime' require 'poise_application_ruby/app_mixin' module PoiseApplicationRuby module Resources # (see Ruby::Resource) # @since 4.0.0 module Ruby # An `application_ruby` resource to manage Ruby runtimes # inside an Application cookbook deployment. # # @provides application_ruby # @provides application_ruby_runtime # @action install # @action uninstall # @example # application '/app' do # ruby '2' # end class Resource < PoiseRuby::Resources::RubyRuntime::Resource include PoiseApplicationRuby::AppMixin provides(:application_ruby) provides(:application_ruby_runtime) container_default(false) subclass_providers! # Rebind the parent class #gem_binary instead of the one from # RubyCommandMixin (by way of AppMixin) def gem_binary(*args, &block) self.class.superclass.instance_method(:gem_binary).bind(self).call(*args, &block) end # Set this resource as the app_state's parent ruby. # # @api private def after_created super.tap do |val| app_state_ruby(self) end end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
poise/application_ruby
https://github.com/poise/application_ruby/blob/aa3cd8758f6eef7ff4620e3781dfc68380d7c978/lib/poise_application_ruby/resources/unicorn.rb
lib/poise_application_ruby/resources/unicorn.rb
# # Copyright 2015-2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider' require 'chef/resource' require 'poise_application_ruby/service_mixin' module PoiseApplicationRuby module Resources # (see Unicorn::Resource) # @since 4.0.0 module Unicorn # An `application_unicorn` resource to manage a unicorn web application # server. # # @since 4.0.0 # @provides application_unicorn # @action enable # @action disable # @action start # @action stop # @action restart # @action reload # @example # application '/srv/myapp' do # git '...' # bundle_install # unicorn do # port 8080 # end # end class Resource < Chef::Resource include PoiseApplicationRuby::ServiceMixin provides(:application_unicorn) # @!attribute port # Port to bind to. attribute(:port, kind_of: [String, Integer], default: 80) end # Provider for `application_unicorn`. # # @since 4.0.0 # @see Resource # @provides application_unicorn class Provider < Chef::Provider include PoiseApplicationRuby::ServiceMixin provides(:application_unicorn) private # Find the path to the config.ru. If the resource path was to a # directory, apparent /config.ru. # # @return [String] def configru_path @configru_path ||= if ::File.directory?(new_resource.path) ::File.join(new_resource.path, 'config.ru') else new_resource.path end end # Set service resource options. def service_options(resource) super resource.ruby_command("unicorn --port #{new_resource.port} #{configru_path}") end end end end end
ruby
Apache-2.0
aa3cd8758f6eef7ff4620e3781dfc68380d7c978
2026-01-04T17:55:52.872045Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/test/model_test.rb
test/model_test.rb
require File.expand_path(File.join(File.dirname(__FILE__), "test_helper")) class ModelTest < Test::Unit::TestCase class Poro include Informal::Model attr_accessor :x, :y, :z validates_presence_of :x, :y, :z end def poro_class; Poro; end include ModelTestCases end
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/test/test_helper.rb
test/test_helper.rb
require "test/unit" require "rubygems" require "bundler/setup" require "informal/model" require "informal/model_no_init" require File.expand_path(File.join(File.dirname(__FILE__), "model_test_cases"))
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/test/model_no_init_test.rb
test/model_no_init_test.rb
require File.expand_path(File.join(File.dirname(__FILE__), "test_helper")) class ModelNoInitTest < Test::Unit::TestCase class KalEl attr_accessor :k def initialize(uber) @k = uber end end class Poro < KalEl include Informal::ModelNoInit attr_accessor :x, :y, :z validates_presence_of :x, :y, :z def initialize(attrs={}) super(true) self.attributes = attrs end end def poro_class; Poro; end include ModelTestCases def test_super assert @model.k end end
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/test/model_test_cases.rb
test/model_test_cases.rb
module ModelTestCases include ActiveModel::Lint::Tests def setup @model = self.poro_class.new(:x => 1, :y => 2) end def teardown self.poro_class.instance_variable_set(:@_model_name, nil) end def test_new assert_equal 1, @model.x assert_equal 2, @model.y assert_nil @model.z end def test_new_with_nil assert_nothing_raised { self.poro_class.new(nil) } end def test_persisted assert !@model.persisted? end def test_new_record assert @model.new_record? end def test_to_key assert_equal [@model.object_id], @model.to_key end def test_naming assert_equal "Poro", @model.class.model_name.human end if ActiveModel::VERSION::MINOR > 0 def test_model_name_override self.poro_class.informal_model_name("Alias") assert_equal "Alias", @model.class.model_name.human end end def test_validations assert @model.invalid? assert_equal [], @model.errors[:x] assert @model.errors[:z].any? {|err| err =~ /blank/} end end
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/lib/informal.rb
lib/informal.rb
require "informal/model"
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/lib/informal/model_no_init.rb
lib/informal/model_no_init.rb
require "active_model" module Informal module ModelNoInit def self.included(klass) klass.class_eval do extend ActiveModel::Naming include ActiveModel::Validations extend ClassMethods end end module ClassMethods if ActiveModel::VERSION::MINOR > 0 def informal_model_name(name) @_model_name = ActiveModel::Name.new(self, nil, name) end end end def attributes=(attrs) attrs && attrs.each_pair { |name, value| self.send("#{name}=", value) } end def persisted? false end def new_record? true end def to_model self end def to_key [object_id] end def to_param nil end end end
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/lib/informal/version.rb
lib/informal/version.rb
module Informal VERSION = "0.1.0" end
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
joshsusser/informal
https://github.com/joshsusser/informal/blob/d9658e30dafd2e55f11ec1e52f9b111d6bc96f39/lib/informal/model.rb
lib/informal/model.rb
require "informal/model_no_init" module Informal module Model def self.included(klass) klass.class_eval do include ModelNoInit end end def initialize(attrs={}) self.attributes = attrs end end end
ruby
MIT
d9658e30dafd2e55f11ec1e52f9b111d6bc96f39
2026-01-04T17:55:52.973594Z
false
yabeda-rb/yabeda-prometheus
https://github.com/yabeda-rb/yabeda-prometheus/blob/50398b155055631596fac238997812a7705fdac3/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require "bundler/setup" require "yabeda/prometheus" require "pry" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.order = :random config.expect_with :rspec do |c| c.syntax = :expect end end
ruby
MIT
50398b155055631596fac238997812a7705fdac3
2026-01-04T17:55:50.186689Z
false
yabeda-rb/yabeda-prometheus
https://github.com/yabeda-rb/yabeda-prometheus/blob/50398b155055631596fac238997812a7705fdac3/spec/yabeda/prometheus_spec.rb
spec/yabeda/prometheus_spec.rb
# frozen_string_literal: true RSpec.describe Yabeda::Prometheus do it "has a version number" do expect(Yabeda::Prometheus::VERSION).not_to be nil end before(:each) do Yabeda.configure do group :test counter :counter, comment: 'Test counter', tags: [:ctag] gauge :gauge, comment: 'Test gauge', tags: [:gtag] histogram :histogram, comment: 'Test histogram', tags: [:htag], buckets: [1, 5, 10] summary :summary, comment: 'Test summary', tags: [:stag] end Yabeda.register_adapter(:prometheus, Yabeda::Prometheus::Adapter.new) Yabeda.configure! end after(:each) do Yabeda.metrics.keys.each(&Yabeda::Prometheus.registry.method(:unregister)) Yabeda.reset! end context 'counters' do specify 'increment of yabeda counter increments prometheus counter' do expect { Yabeda.test.counter.increment({ ctag: 'ctag-value' }) }.to change { Yabeda::Prometheus.registry.get('test_counter')&.get(labels: { ctag: 'ctag-value' }) || 0 }.by 1.0 end end context 'gauges' do specify 'set of yabeda gauge sets prometheus gauge' do expect { Yabeda.test.gauge.set({ gtag: 'gtag-value' }, 42) }.to change { Yabeda::Prometheus.registry.get('test_gauge')&.get(labels: { gtag: 'gtag-value' }) || 0 }.to 42.0 end end context 'histograms' do specify 'measure of yabeda histogram measures prometheus histogram' do expect { Yabeda.test.histogram.measure({ htag: 'htag-value' }, 7.5) }.to change { Yabeda::Prometheus.registry.get('test_histogram')&.get(labels: { htag: 'htag-value' }) || {} }.to({ "1" => 0.0, "5" => 0.0, "10" => 1.0, "+Inf" => 1.0, "sum" => 7.5 }) end end context 'summaries' do specify 'observation of yabeda summary observes prometheus summary' do expect { Yabeda.test.summary.observe({ stag: 'stag-value' }, 42) }.to change { Yabeda::Prometheus.registry.get('test_summary')&.get(labels: { stag: 'stag-value' }) || {} }.to({ "sum" => 42.0, "count" => 1.0 }) end end context 'rack' do it "should render metrics for consuming by Prometheus" do rack = Yabeda::Prometheus::Exporter.rack_app env = { 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/metrics' } response = rack.call(env).last.join expect(response).not_to match(/test_counter{.+} \d+/) expect(response).not_to match(/test_gauge{.+} \d+/) expect(response).not_to match(/test_histogram{.+} \d+/) Yabeda.test_counter.increment({ ctag: :'ctag-value' }) Yabeda.test_gauge.set({ gtag: :'gtag-value' }, 123) Yabeda.test_histogram.measure({ htag: :'htag-value' }, 7) response = rack.call(env).last.join expect(response).to match(/test_counter{.+} 1\.0/) expect(response).to match(/test_gauge{.+} 123\.0/) expect(response).to match(/test_histogram_bucket{.+,le="10"} 1\.0/) end end end
ruby
MIT
50398b155055631596fac238997812a7705fdac3
2026-01-04T17:55:50.186689Z
false
yabeda-rb/yabeda-prometheus
https://github.com/yabeda-rb/yabeda-prometheus/blob/50398b155055631596fac238997812a7705fdac3/lib/yabeda/prometheus.rb
lib/yabeda/prometheus.rb
# frozen_string_literal: true require "yabeda" require "prometheus/client" require "prometheus/client/push" require "yabeda/prometheus/version" require "yabeda/prometheus/adapter" require "yabeda/prometheus/exporter" module Yabeda module Prometheus class << self def registry ::Prometheus::Client.registry end def push_gateway @push_gateway ||= ::Prometheus::Client::Push.new( job: ENV.fetch("PROMETHEUS_JOB_NAME", "yabeda"), gateway: ENV.fetch("PROMETHEUS_PUSH_GATEWAY", "http://localhost:9091"), open_timeout: 5, read_timeout: 30, ) end end end end
ruby
MIT
50398b155055631596fac238997812a7705fdac3
2026-01-04T17:55:50.186689Z
false
yabeda-rb/yabeda-prometheus
https://github.com/yabeda-rb/yabeda-prometheus/blob/50398b155055631596fac238997812a7705fdac3/lib/yabeda/prometheus/version.rb
lib/yabeda/prometheus/version.rb
# frozen_string_literal: true module Yabeda module Prometheus VERSION = "0.9.1" end end
ruby
MIT
50398b155055631596fac238997812a7705fdac3
2026-01-04T17:55:50.186689Z
false
yabeda-rb/yabeda-prometheus
https://github.com/yabeda-rb/yabeda-prometheus/blob/50398b155055631596fac238997812a7705fdac3/lib/yabeda/prometheus/exporter.rb
lib/yabeda/prometheus/exporter.rb
# frozen_string_literal: true require "prometheus/middleware/exporter" require "rack" require "logger" module Yabeda module Prometheus # Rack application or middleware that provides metrics exposition endpoint class Exporter < ::Prometheus::Middleware::Exporter NOT_FOUND_HANDLER = lambda do |_env| [404, { "Content-Type" => "text/plain" }, ["Not Found\n"]] end.freeze class << self # Allows to use middleware as standalone rack application def call(env) options = env.fetch("action_dispatch.request.path_parameters", {}) @app ||= new(NOT_FOUND_HANDLER, path: "/", **options) @app.call(env) end def start_metrics_server!(webrick_options: {}, **rack_app_options) Thread.new do default_port = ENV.fetch("PORT", 9394) rack_handler.run( rack_app(**rack_app_options), Host: ENV["PROMETHEUS_EXPORTER_BIND"] || "0.0.0.0", Port: ENV.fetch("PROMETHEUS_EXPORTER_PORT", default_port), AccessLog: [], **webrick_options, ) end end def rack_app(exporter = self, logger: Logger.new(IO::NULL), use_deflater: true, **exporter_options) ::Rack::Builder.new do use ::Rack::Deflater if use_deflater use ::Rack::CommonLogger, logger use ::Rack::ShowExceptions use exporter, **exporter_options run NOT_FOUND_HANDLER end end def rack_handler if Gem.loaded_specs['rack']&.version&.>= Gem::Version.new('3.0') require 'rackup' ::Rackup::Handler::WEBrick else ::Rack::Handler::WEBrick end rescue LoadError warn 'Please add gems rackup and webrick to your Gemfile to expose Yabeda metrics from prometheus-mmap' ::Rack::Handler::WEBrick end end def initialize(app, options = {}) super(app, options.merge(registry: Yabeda::Prometheus.registry)) end def call(env) ::Yabeda.collect! if env["PATH_INFO"] == path if ::Yabeda.debug? result = nil ::Yabeda.prometheus_exporter.render_duration.measure({}) do result = super end result else super end end end end end
ruby
MIT
50398b155055631596fac238997812a7705fdac3
2026-01-04T17:55:50.186689Z
false
yabeda-rb/yabeda-prometheus
https://github.com/yabeda-rb/yabeda-prometheus/blob/50398b155055631596fac238997812a7705fdac3/lib/yabeda/prometheus/adapter.rb
lib/yabeda/prometheus/adapter.rb
# frozen_string_literal: true require "prometheus/client" require 'prometheus/client/data_stores/direct_file_store' require 'prometheus/client/data_stores/single_threaded' require "yabeda/base_adapter" module Yabeda class Prometheus::Adapter < BaseAdapter class UndeclaredMetricTags < RuntimeError attr_reader :message def initialize(metric_name, caused_exception) @message = <<~MESSAGE.strip Prometheus requires all used tags to be declared at metric registration time. \ Please add `tags` option to the declaration of metric `#{metric_name}`. \ Error: #{caused_exception.message} MESSAGE end end def registry @registry ||= ::Prometheus::Client.registry end def register_counter!(metric) validate_metric!(metric) registry.counter( build_name(metric), docstring: metric.comment, labels: Array(metric.tags), store_settings: store_settings(metric), ) end def perform_counter_increment!(metric, tags, value) registry.get(build_name(metric)).increment(by: value, labels: tags) rescue ::Prometheus::Client::LabelSetValidator::InvalidLabelSetError => e raise UndeclaredMetricTags.new(build_name(metric), e) end def register_gauge!(metric) validate_metric!(metric) registry.gauge( build_name(metric), docstring: metric.comment, labels: Array(metric.tags), store_settings: store_settings(metric), ) end def perform_gauge_set!(metric, tags, value) registry.get(build_name(metric)).set(value, labels: tags) rescue ::Prometheus::Client::LabelSetValidator::InvalidLabelSetError => e raise UndeclaredMetricTags.new(build_name(metric), e) end def register_histogram!(metric) validate_metric!(metric) buckets = metric.buckets || ::Prometheus::Client::Histogram::DEFAULT_BUCKETS registry.histogram( build_name(metric), docstring: metric.comment, buckets: buckets, labels: Array(metric.tags), store_settings: store_settings(metric), ) end def perform_histogram_measure!(metric, tags, value) registry.get(build_name(metric)).observe(value, labels: tags) rescue ::Prometheus::Client::LabelSetValidator::InvalidLabelSetError => e raise UndeclaredMetricTags.new(build_name(metric), e) end def register_summary!(metric) validate_metric!(metric) registry.summary( build_name(metric), docstring: metric.comment, labels: Array(metric.tags), store_settings: store_settings(metric), ) end def perform_summary_observe!(metric, tags, value) registry.get(build_name(metric)).observe(value, labels: tags) rescue ::Prometheus::Client::LabelSetValidator::InvalidLabelSetError => e raise UndeclaredMetricTags.new(build_name(metric), e) end def build_name(metric) [metric.group, metric.name, metric.unit].compact.join('_').to_sym end def validate_metric!(metric) return if metric.comment raise ArgumentError, 'Prometheus require metrics to have comments' end def debug! Yabeda.configure do group :prometheus_exporter histogram :render_duration, tags: %i[], unit: :seconds, buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10], comment: "Time required to render all metrics in Prometheus format" end end private # @param metric [Yabeda::Metric] # @return [Hash] def store_settings(metric) case ::Prometheus::Client.config.data_store when ::Prometheus::Client::DataStores::Synchronized, ::Prometheus::Client::DataStores::SingleThreaded {} # Default synchronized store doesn't allow to pass any options when ::Prometheus::Client::DataStores::DirectFileStore, ::Object # Anything else { aggregation: metric.aggregation }.compact end end Yabeda.register_adapter(:prometheus, new) end end
ruby
MIT
50398b155055631596fac238997812a7705fdac3
2026-01-04T17:55:50.186689Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/spec/response_spec.rb
spec/response_spec.rb
require 'spec_helper' describe Coinbase::Exchange do before :all do @obj = Coinbase::Exchange::APIObject.new('text' => 'test 123', 'decimal' => '123456.789', 'btc' => '฿ 1.23456789', 'usd' => '$ 1,234,567.89', 'gbp' => '£ 1,234,567.89', 'eur' => '€ 1,234,567.89') end it "doesn't do anything to generic text" do expect(@obj.text.class).to eq(String) end it "converts numeric string to bigdecimal" do expect(@obj.decimal.class).to eq(BigDecimal) end it "converts currency to bigdecimal" do expect(@obj.btc.class).to eq(BigDecimal) expect(@obj.usd.class).to eq(BigDecimal) expect(@obj.gbp.class).to eq(BigDecimal) expect(@obj.eur.class).to eq(BigDecimal) end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/spec/synchronous_spec.rb
spec/synchronous_spec.rb
require 'spec_helper' describe Coinbase::Exchange::Client do before :all do @client = Coinbase::Exchange::Client.new 'api_pass', 'api_key', 'api_secret' end it "responds to all endpoints" do endpoints.each do |ref| expect(@client).to respond_to(ref) end end it "makes requests synchronously" do stub_request(:get, /.*/).to_return(body: mock_collection.to_json) success = true EM.run do @client.orders { EM.stop } success = false end expect(success) end it "gets currencies" do stub_request(:get, /currencies/).to_return(body: mock_collection.to_json) @client.currencies do |out| out.each do |item| expect(item.class).to eq(Coinbase::Exchange::APIObject) expect(item).to eq(mock_item) end end end it "gets products" do stub_request(:get, /products/).to_return(body: mock_collection.to_json) @client.products do |out| out.each do |item| expect(item.class).to eq(Coinbase::Exchange::APIObject) expect(item).to eq(mock_item) end end end it "gets BTC-USD ticker by default" do stub_request(:get, /products.BTC-USD.ticker/) .to_return(body: mock_item.to_json) @client.last_trade do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out).to eq(mock_item) end end it "gets arbitrary ticker" do stub_request(:get, /products.BTC-LTC.ticker/) .to_return(body: mock_item.to_json) @client.last_trade(product_id: "BTC-LTC") do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out).to eq(mock_item) end end it "gets trade history" do # FIXME end it "gets order history" do # FIXME end it "gets accounts" do stub_request(:get, /accounts/).to_return(body: mock_collection.to_json) @client.accounts do |out| out.each do |item| expect(item.class).to eq(Coinbase::Exchange::APIObject) expect(item).to eq(mock_item) end end end it "gets account" do stub_request(:get, /accounts.test/).to_return(body: mock_item.to_json) @client.account("test") do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out).to eq(mock_item) end end it "gets account history" do stub_request(:get, /accounts.test.ledger/) .to_return(body: mock_collection.to_json) @client.account_history("test") do |out| out.each do |item| # FIXME: Add a check for correct model expect(item).to eq(mock_item) end end end it "gets account holds" do stub_request(:get, /accounts.test.holds/) .to_return(body: mock_collection.to_json) @client.account_holds("test") do |out| out.each do |item| expect(item.class).to eq(Coinbase::Exchange::APIObject) expect(item).to eq(mock_item) end end end it "places a bid" do stub_request(:post, /orders/) .with(body: hash_including('side' => 'buy')) .to_return(body: mock_item.to_json) @client.bid(10, 250) do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out['status']).to eq('OK') end end it "places an ask" do stub_request(:post, /orders/) .with(body: hash_including('side' => 'sell')) .to_return(body: mock_item.to_json) @client.ask(10, 250) do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out['status']).to eq('OK') end end it "cancels an order" do stub_request(:delete, /orders.test/).to_return(body: nil) @client.cancel('test') do |out| expect(out).to eq({}) end end it "gets orders" do stub_request(:get, /orders/).to_return(body: mock_collection.to_json) @client.orders do |out| out.each do |item| expect(item.class).to eq(Coinbase::Exchange::APIObject) expect(item['status']).to eq('OK') end end end it "gets an order" do stub_request(:get, /orders.test/).to_return(body: mock_item.to_json) @client.order('test') do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out['status']).to eq('OK') end end it "gets fills" do stub_request(:get, /fills/).to_return(body: mock_collection.to_json) @client.fills do |out| out.each do |item| expect(item.class).to eq(Coinbase::Exchange::APIObject) expect(item['status']).to eq('OK') end end end it "makes a deposit" do stub_request(:post, /transfers/) .with(body: hash_including('type' => 'deposit')) .to_return(body: mock_item.to_json) @client.deposit(SecureRandom.uuid, 10) do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out['status']).to eq('OK') end end it "makes a withdrawal" do stub_request(:post, /transfers/) .with(body: hash_including('type' => 'withdraw')) .to_return(body: mock_item.to_json) @client.withdraw(SecureRandom.uuid, 10) do |out| expect(out.class).to eq(Coinbase::Exchange::APIObject) expect(out['status']).to eq('OK') end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/spec/async_spec.rb
spec/async_spec.rb
require 'spec_helper' describe Coinbase::Exchange::AsyncClient do before :all do @client = Coinbase::Exchange::AsyncClient.new('api_pass', 'api_key', 'api_secret') end it "makes asynchronous requests" do stub_request(:get, /.*/).to_return(body: mock_collection.to_json) success = false EM.run do @client.orders { EM.stop } success = true end expect(success) end it "raises BadRequestError on 400" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 400) expect do EM.run { @client.orders { EM.stop } } end.to raise_error Coinbase::Exchange::BadRequestError end it "raises NotAuthorizedError on 401" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 401) expect do EM.run { @client.orders { EM.stop } } end.to raise_error Coinbase::Exchange::NotAuthorizedError end it "raises ForbiddenError on 403" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 403) expect do EM.run { @client.orders { EM.stop } } end.to raise_error Coinbase::Exchange::ForbiddenError end it "raises NotFoundError on 404" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 404) expect do EM.run { @client.orders { EM.stop } } end.to raise_error Coinbase::Exchange::NotFoundError end it "raises RateLimitError on 429" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 429) expect do EM.run { @client.orders { EM.stop } } end.to raise_error Coinbase::Exchange::RateLimitError end it "raises InternalServerError on 500" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 500) expect do EM.run { @client.orders { EM.stop } } end.to raise_error Coinbase::Exchange::InternalServerError end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/spec/error_spec.rb
spec/error_spec.rb
require 'spec_helper' describe Coinbase::Exchange do before :all do @client = Coinbase::Exchange::Client.new 'api_pass', 'api_key', 'api_secret' end it "raises BadRequestError on 400" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 400) expect { @client.orders }.to raise_error Coinbase::Exchange::BadRequestError end it "raises NotAuthorizedError on 401" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 401) expect { @client.orders }.to raise_error Coinbase::Exchange::NotAuthorizedError end it "raises ForbiddenError on 403" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 403) expect { @client.orders }.to raise_error Coinbase::Exchange::ForbiddenError end it "raises NotFoundError on 404" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 404) expect { @client.orders }.to raise_error Coinbase::Exchange::NotFoundError end it "raises RateLimitError on 429" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 429) expect { @client.orders }.to raise_error Coinbase::Exchange::RateLimitError end it "raises InternalServerError on 500" do stub_request(:get, /.*/) .to_return(body: mock_item.to_json, status: 500) expect { @client.orders }.to raise_error Coinbase::Exchange::InternalServerError end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/spec/websocket_spec.rb
spec/websocket_spec.rb
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/spec/spec_helper.rb
spec/spec_helper.rb
require 'bundler/setup' require 'webmock/rspec' require 'em-http' Bundler.setup require 'coinbase/exchange' MARKET_REFS = [ :currencies, :products, :orderbook, :last_trade, :trade_history, :price_history, :daily_stats ] ACCOUNT_REFS = [ :accounts, :account, :account_history, :account_holds ] ORDER_REFS = [ :bid, :ask, :cancel, :orders, :order, :fills ] TRANSFER_REFS = [ :deposit, :withdraw ] def endpoints (MARKET_REFS << ACCOUNT_REFS << ORDER_REFS << TRANSFER_REFS).flatten! end def mock_item { 'id' => 'test', 'status' => 'OK' } end def mock_collection [ mock_item, mock_item ] end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange.rb
lib/coinbase/exchange.rb
require "bigdecimal" require "json" require "uri" require "net/http" require "em-http-request" require "faye/websocket" require "coinbase/exchange/errors" require "coinbase/exchange/api_object" require "coinbase/exchange/api_response" require "coinbase/exchange/api_client.rb" require "coinbase/exchange/adapters/net_http.rb" require "coinbase/exchange/adapters/em_http.rb" require "coinbase/exchange/client" require "coinbase/exchange/websocket" module Coinbase # Coinbase Exchange module module Exchange end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/version.rb
lib/coinbase/exchange/version.rb
module Coinbase # Gem version module Exchange VERSION = "0.2.0" end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/errors.rb
lib/coinbase/exchange/errors.rb
module Coinbase module Exchange # # Websocket Errors # class WebsocketError < RuntimeError end class DroppedPackets < WebsocketError end # # Rest API Errors # class APIError < RuntimeError end # Status 400 class BadRequestError < APIError end # Status 401 class NotAuthorizedError < APIError end # Status 403 class ForbiddenError < APIError end # Status 404 class NotFoundError < APIError end # Status 429 class RateLimitError < APIError end # Status 500 class InternalServerError < APIError end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/api_object.rb
lib/coinbase/exchange/api_object.rb
module Coinbase module Exchange # Response item abstract model class APIObject < Hash def initialize(data) super update(data) end def update(data) return if data.nil? data.each { |key, val| self[key] = val } if data.is_a?(Hash) end def format(var) return if var.nil? # Looks like a number or currency if var =~ /^.{0,1}\s*[0-9,]*\.{0,1}[0-9]*$/ BigDecimal(var.gsub(/[^0-9\.\-]/, '')) else var end end # This is common enough that we should override the hash method def size format(self['size']) || super end def method_missing(method, *args, &blk) format(self[method.to_s]) || super end def respond_to_missing?(method, include_all = false) self.key?(method.to_s) || super end end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/api_response.rb
lib/coinbase/exchange/api_response.rb
module Coinbase module Exchange # Encapsulate data for an API response class APIResponse attr_reader :received_at def initialize(resp) @received_at = Time.now @response = resp end def raw @response end def body fail NotImplementedError end def headers fail NotImplementedError end def status fail NotImplementedError end end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/client.rb
lib/coinbase/exchange/client.rb
module Coinbase module Exchange class Client < NetHTTPClient end class AsyncClient < EMHTTPClient end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/api_client.rb
lib/coinbase/exchange/api_client.rb
module Coinbase module Exchange # Net-http client for Coinbase Exchange API class APIClient def initialize(api_key = '', api_secret = '', api_pass = '', options = {}) @api_uri = URI.parse(options[:api_url] || "https://api.pro.coinbase.com") @api_pass = api_pass @api_key = api_key @api_secret = api_secret @default_product = options[:product_id] || "BTC-USD" end def server_epoch(params = {}) get("/time", params) do |resp| yield(resp) if block_given? end end # # Market Data # def currencies(params = {}) out = nil get("/currencies", params) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end def products(params = {}) out = nil get("/products", params) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end def orderbook(params = {}) product = params[:product_id] || @default_product out = nil get("/products/#{product}/book", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end def last_trade(params = {}) product = params[:product_id] || @default_product out = nil get("/products/#{product}/ticker", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end def trade_history(params = {}) product = params[:product_id] || @default_product out = nil get("/products/#{product}/trades", params, paginate: true) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end def price_history(params = {}) product = params[:product_id] || @default_product out = nil get("/products/#{product}/candles", params) do |resp| out = response_collection( resp.map do |item| { 'start' => Time.at(item[0]), 'low' => item[1], 'high' => item[2], 'open' => item[3], 'close' => item[4], 'volume' => item[5] } end ) yield(out, resp) if block_given? end out end def daily_stats(params = {}) product = params[:product_id] || @default_product out = nil get("/products/#{product}/stats", params) do |resp| resp["start"] = (Time.now - 24 * 60 * 60).to_s out = response_object(resp) yield(out, resp) if block_given? end out end # # Accounts # def accounts(params = {}) out = nil get("/accounts", params) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end def account(id, params = {}) out = nil get("/accounts/#{id}", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end def account_history(id, params = {}) out = nil get("/accounts/#{id}/ledger", params, paginate: true) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end def account_holds(id, params = {}) out = nil get("/accounts/#{id}/holds", params, paginate: true) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end # # Orders # def bid(amt, price, params = {}) params[:product_id] ||= @default_product params[:size] = amt params[:price] = price params[:side] = "buy" out = nil post("/orders", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end alias_method :buy, :bid def ask(amt, price, params = {}) params[:product_id] ||= @default_product params[:size] = amt params[:price] = price params[:side] = "sell" out = nil post("/orders", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end alias_method :sell, :ask def cancel(id) out = nil delete("/orders/#{id}") do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end def orders(params = {}) params[:status] ||= "all" out = nil get("/orders", params, paginate: true) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end def order(id, params = {}) out = nil get("/orders/#{id}", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end def fills(params = {}) out = nil get("/fills", params, paginate: true) do |resp| out = response_collection(resp) yield(out, resp) if block_given? end out end # # Transfers # def deposit(account_id, amt, params = {}) params[:type] = "deposit" params[:coinbase_account_id] = account_id params[:amount] = amt out = nil post("/transfers", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end def withdraw(account_id, amt, params = {}) params[:type] = "withdraw" params[:coinbase_account_id] = account_id params[:amount] = amt out = nil post("/transfers", params) do |resp| out = response_object(resp) yield(out, resp) if block_given? end out end private def response_collection(resp) out = resp.map { |item| APIObject.new(item) } out.instance_eval { @response = resp } add_metadata(out) out end def response_object(resp) out = APIObject.new(resp) out.instance_eval { @response = resp.response } add_metadata(out) out end def add_metadata(resp) resp.instance_eval do def response @response end def raw @response.raw end def response_headers @response.headers end def response_status @response.status end end resp end def get(path, params = {}, options = {}) params[:limit] ||= 100 if options[:paginate] == true http_verb('GET', "#{path}?#{URI.encode_www_form(params)}") do |resp| begin out = JSON.parse(resp.body) rescue JSON::ParserError out = resp.body end out.instance_eval { @response = resp } add_metadata(out) if options[:paginate] && out.count == params[:limit] params[:after] = resp.headers['CB-AFTER'] # Stop fething whenever the :after cursor crosses # the :before cursor (if present), which means that # we already got everything we need. This is only applicable # when the :before cursor is present. If not present, # `params[:before].to_i` returns 0 and we will continue fetching # everything until the very last page. if (params[:after].to_i + 1) > params[:before].to_i get(path, params, options) do |pages| out += pages add_metadata(out) yield(out) end else yield(out) end else yield(out) end end end def post(path, params = {}) http_verb('POST', path, params.to_json) do |resp| begin out = JSON.parse(resp.body) rescue JSON::ParserError out = resp.body end out.instance_eval { @response = resp } add_metadata(out) yield(out) end end def delete(path) http_verb('DELETE', path) do |resp| begin out = JSON.parse(resp.body) rescue out = resp.body end out.instance_eval { @response = resp } add_metadata(out) yield(out) end end def http_verb(_method, _path, _body) fail NotImplementedError end def self.whitelisted_certificates path = File.expand_path(File.join(File.dirname(__FILE__), 'ca-coinbase.crt')) certs = [ [] ] File.readlines(path).each do |line| next if ["\n", "#"].include?(line[0]) certs.last << line certs << [] if line == "-----END CERTIFICATE-----\n" end result = OpenSSL::X509::Store.new certs.each do |lines| next if lines.empty? cert = OpenSSL::X509::Certificate.new(lines.join) result.add_cert(cert) end result end end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false