repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
martinhristov90/packer-consul
|
test/integration/consul/controls/consul_directory.rb
|
control 'consul_directory' do
title 'consul_directory_check'
desc 'Checks if Consul directory is created and has the right permissions'
describe directory('/etc/consul.d/') do
it { should exist }
its('owner') { should eq 'consul' }
its('mode') { should cmp '0755' }
end
end
|
martinhristov90/packer-consul
|
test/integration/consul/controls/consul_systemd.rb
|
<filename>test/integration/consul/controls/consul_systemd.rb
control 'consul_systemd' do
title 'consul_check_systemd'
desc 'Checks if Consul is installed as Systemd service'
describe systemd_service('consul') do
it { should be_installed }
it { should_not be_enabled }
it { should_not be_running }
end
end
|
martinhristov90/packer-consul
|
test/integration/consul/controls/consul_install.rb
|
control 'consul_install' do
title 'consul_install_check'
desc 'Checks if Consul is installed'
describe command('consul') do
it { should exist }
end
describe command('consul-template') do
it { should exist }
end
describe command('envconsul') do
it { should exist }
end
end
|
martinhristov90/packer-consul
|
test/integration/consul/controls/consul_user.rb
|
control 'consul_user' do
title 'consul_user_check'
desc 'Checks if user consul is available'
describe group('consul') do
it { should exist }
end
describe user('consul') do
it { should exist }
its('shell') { should eq '/bin/false' }
its('group') { should eq 'consul' }
its('home') { should eq '/etc/consul.d' }
end
end
|
remore/yarv-prof
|
yarv-prof.gemspec
|
<gh_stars>0
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'yarv-prof/version'
Gem::Specification.new do |s|
s.name = 'yarv-prof'
s.version = YarvProf::VERSION
s.homepage = 'https://github.com/remore/yarv-prof'
s.authors = '<NAME>(@remore)'
s.email = '<EMAIL>'
s.files = `git ls-files`.split("\n")
s.bindir = 'bin'
s.executables = 'yarv-prof'
s.summary = 'A DTrace-based YARV profiler'
s.description = "yarv-prof does nothing special to profile YARV behavior, just heavily depends on Ruby's DTrace probes support. If you are looking for something useful to utilize Ruby's DTrace feature, yarv-prof may work for you."
s.license = 'MIT'
s.add_dependency "enumerable-statistics"
end
|
remore/yarv-prof
|
lib/yarv-prof.rb
|
<filename>lib/yarv-prof.rb<gh_stars>0
require 'yarv-prof/version'
require 'tempfile'
class YarvProf
class << self
def start(clock: :wall, out:'/tmp/yarv-prof/', opt:'-x bufsize=20m')
at_exit do
Process.kill(:TERM, @pid) if !@pid.nil?
FileUtils.remove_entry @file.path if File.exists?(@file.path)
end
measure_mode = clock == :cpu ? "vtimestamp" : "timestamp"
@file = Tempfile.new('.yarv-prof.d')
@file.puts <<EOS
dtrace:::BEGIN{
printf("insn,#{measure_mode}\\n");
}
ruby#{Process.pid}:::insn{
printf("%s,%d\\n", copyinstr(arg0), #{measure_mode});
}
EOS
@file.close
FileUtils.mkdir out if !File.directory?(out)
dumpfile = out + Time.now.strftime('%Y%m%d_%H%M%S.dump')
@pid = Process.spawn("dtrace -q -s '#{@file.path}' #{opt}", :err => :out,:out => dumpfile)
`size=0;while [ $size -le 10 ];do size=$(wc -c < #{dumpfile});sleep 0.01;done`
end
def end
sleep 1 # sleep here otherwise the log file will be empty
Process.kill(:TERM, @pid) if !@pid.nil?
end
end
end
|
remore/yarv-prof
|
lib/yarv-prof/version.rb
|
<reponame>remore/yarv-prof<filename>lib/yarv-prof/version.rb
class YarvProf
VERSION = "0.1.1"
end
|
stevenspiel/formbuilder-js-rails
|
lib/formbuilder/formbuilder-js-rails.rb
|
<gh_stars>0
require "formbuilder/js/rails/version"
module Formbuilder
module Js
module Rails
# Your code goes here...
end
end
end
|
stevenspiel/formbuilder-js-rails
|
lib/formbuilder/js/rails/version.rb
|
<filename>lib/formbuilder/js/rails/version.rb
module Formbuilder
module Js
module Rails
VERSION = "0.0.2"
end
end
end
|
camptocamp/vagrant-debian-package
|
test/unit/vagrant/registry_test.rb
|
require File.expand_path("../../base", __FILE__)
describe Vagrant::Registry do
let(:instance) { described_class.new }
it "should return nil for nonexistent items" do
instance.get("foo").should be_nil
end
it "should register a simple key/value" do
instance.register("foo") { "value" }
instance.get("foo").should == "value"
end
it "should register an item without calling the block yet" do
expect do
instance.register("foo") do
raise Exception, "BOOM!"
end
end.to_not raise_error
end
it "should raise an error if no block is given" do
expect { instance.register("foo") }.
to raise_error(ArgumentError)
end
it "should call and return the result of a block when asking for the item" do
object = Object.new
instance.register("foo") do
object
end
instance.get("foo").should eql(object)
end
it "should be able to get the item with []" do
object = Object.new
instance.register("foo") { object }
instance["foo"].should eql(object)
end
it "should cache the result of the item so they can be modified" do
# Make the proc generate a NEW array each time
instance.register("foo") { [] }
# Test that modifying the result modifies the actual cached
# value. This verifies we're caching.
instance.get("foo").should == []
instance.get("foo") << "value"
instance.get("foo").should == ["value"]
end
it "should be able to check if a key exists" do
instance.register("foo") { "bar" }
instance.should have_key("foo")
instance.should_not have_key("bar")
end
it "should be enumerable" do
instance.register("foo") { "foovalue" }
instance.register("bar") { "barvalue" }
keys = []
values = []
instance.each do |key, value|
keys << key
values << value
end
keys.sort.should == ["bar", "foo"]
values.sort.should == ["barvalue", "foovalue"]
end
it "should be able to convert to a hash" do
instance.register("foo") { "foovalue" }
instance.register("bar") { "barvalue" }
result = instance.to_hash
result.should be_a(Hash)
result["foo"].should == "foovalue"
result["bar"].should == "barvalue"
end
describe "merging" do
it "should merge in another registry" do
one = described_class.new
two = described_class.new
one.register("foo") { raise "BOOM!" }
two.register("bar") { raise "BAM!" }
three = one.merge(two)
expect { three["foo"] }.to raise_error("BOOM!")
expect { three["bar"] }.to raise_error("BAM!")
end
it "should NOT merge in the cache" do
one = described_class.new
two = described_class.new
one.register("foo") { [] }
one["foo"] << 1
two.register("bar") { [] }
two["bar"] << 2
three = one.merge(two)
three["foo"].should == []
three["bar"].should == []
end
end
describe "merge!" do
it "should merge into self" do
one = described_class.new
two = described_class.new
one.register("foo") { "foo" }
two.register("bar") { "bar" }
one.merge!(two)
one["foo"].should == "foo"
one["bar"].should == "bar"
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/plugin/v2/plugin.rb
|
<filename>lib/vagrant/plugin/v2/plugin.rb<gh_stars>0
require "set"
require "log4r"
require "vagrant/plugin/v2/components"
module Vagrant
module Plugin
module V2
# This is the superclass for all V2 plugins.
class Plugin
# Special marker that can be used for action hooks that matches
# all action sequences.
ALL_ACTIONS = :__all_actions__
# The logger for this class.
LOGGER = Log4r::Logger.new("vagrant::plugin::v2::plugin")
# Set the root class up to be ourself, so that we can reference this
# from within methods which are probably in subclasses.
ROOT_CLASS = self
# This returns the manager for all V2 plugins.
#
# @return [V2::Manager]
def self.manager
@manager ||= Manager.new
end
# Returns the {Components} for this plugin.
#
# @return [Components]
def self.components
@components ||= Components.new
end
# Set the name of the plugin. The moment that this is called, the
# plugin will be registered and available. Before this is called, a
# plugin does not exist. The name must be unique among all installed
# plugins.
#
# @param [String] name Name of the plugin.
# @return [String] The name of the plugin.
def self.name(name=UNSET_VALUE)
# Get or set the value first, so we have a name for logging when
# we register.
result = get_or_set(:name, name)
# The plugin should be registered if we're setting a real name on it
Plugin.manager.register(self) if name != UNSET_VALUE
# Return the result
result
end
# Sets a human-friendly descrition of the plugin.
#
# @param [String] value Description of the plugin.
# @return [String] Description of the plugin.
def self.description(value=UNSET_VALUE)
get_or_set(:description, value)
end
# Registers a callback to be called when a specific action sequence
# is run. This allows plugin authors to hook into things like VM
# bootup, VM provisioning, etc.
#
# @param [String] name Name of the action.
# @param [Symbol] hook_name The location to hook. If this isn't
# set, every middleware action is hooked.
# @return [Array] List of the hooks for the given action.
def self.action_hook(name, hook_name=nil, &block)
# The name is currently not used but we want it for the future.
hook_name ||= ALL_ACTIONS
components.action_hooks[hook_name.to_sym] << block
end
# Defines additional command line commands available by key. The key
# becomes the subcommand, so if you register a command "foo" then
# "vagrant foo" becomes available.
#
# @param [String] name Subcommand key.
def self.command(name=UNSET_VALUE, &block)
data[:command] ||= Registry.new
if name != UNSET_VALUE
# Validate the name of the command
if name.to_s !~ /^[-a-z0-9]+$/i
raise InvalidCommandName, "Commands can only contain letters, numbers, and hyphens"
end
# Register a new command class only if a name was given.
data[:command].register(name.to_sym, &block)
end
# Return the registry
data[:command]
end
# Defines additional communicators to be available. Communicators
# should be returned by a block passed to this method. This is done
# to ensure that the class is lazy loaded, so if your class inherits
# from or uses any Vagrant internals specific to Vagrant 1.0, then
# the plugin can still be defined without breaking anything in future
# versions of Vagrant.
#
# @param [String] name Communicator name.
def self.communicator(name=UNSET_VALUE, &block)
data[:communicator] ||= Registry.new
# Register a new communicator class only if a name was given.
data[:communicator].register(name.to_sym, &block) if name != UNSET_VALUE
# Return the registry
data[:communicator]
end
# Defines additional configuration keys to be available in the
# Vagrantfile. The configuration class should be returned by a
# block passed to this method. This is done to ensure that the class
# is lazy loaded, so if your class inherits from any classes that
# are specific to Vagrant 1.0, then the plugin can still be defined
# without breaking anything in future versions of Vagrant.
#
# @param [String] name Configuration key.
def self.config(name, scope=nil, &block)
scope ||= :top
components.configs[scope].register(name.to_sym, &block)
nil
end
# Defines an additionally available guest implementation with
# the given key.
#
# @param [String] name Name of the guest.
# @param [String] parent Name of the parent guest (if any)
def self.guest(name=UNSET_VALUE, parent=nil, &block)
components.guests.register(name.to_sym) do
parent = parent.to_sym if parent
[block.call, parent]
end
nil
end
# Defines a capability for the given guest. The block should return
# a class/module that has a method with the capability name, ready
# to be executed. This means that if it is an instance method,
# the block should return an instance of the class.
#
# @param [String] guest The name of the guest
# @param [String] cap The name of the capability
def self.guest_capability(guest, cap, &block)
components.guest_capabilities[guest.to_sym].register(cap.to_sym, &block)
nil
end
# Defines an additionally available host implementation with
# the given key.
#
# @param [String] name Name of the host.
def self.host(name=UNSET_VALUE, &block)
data[:hosts] ||= Registry.new
# Register a new host class only if a name was given
data[:hosts].register(name.to_sym, &block) if name != UNSET_VALUE
# Return the registry
data[:hosts]
end
# Registers additional providers to be available.
#
# @param [Symbol] name Name of the provider.
def self.provider(name=UNSET_VALUE, options=nil, &block)
components.providers.register(name.to_sym) do
[block.call, options || {}]
end
nil
end
# Registers additional provisioners to be available.
#
# @param [String] name Name of the provisioner.
def self.provisioner(name=UNSET_VALUE, &block)
data[:provisioners] ||= Registry.new
# Register a new provisioner class only if a name was given
data[:provisioners].register(name.to_sym, &block) if name != UNSET_VALUE
# Return the registry
data[:provisioners]
end
# Returns the internal data associated with this plugin. This
# should NOT be called by the general public.
#
# @return [Hash]
def self.data
@data ||= {}
end
protected
# Sentinel value denoting that a value has not been set.
UNSET_VALUE = Object.new
# Helper method that will set a value if a value is given, or otherwise
# return the already set value.
#
# @param [Symbol] key Key for the data
# @param [Object] value Value to store.
# @return [Object] Stored value.
def self.get_or_set(key, value=UNSET_VALUE)
# If no value is to be set, then return the value we have already set
return data[key] if value.eql?(UNSET_VALUE)
# Otherwise set the value
data[key] = value
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/guest.rb
|
require "log4r"
module Vagrant
# This class handles guest-OS specific interactions with a machine.
# It is primarily responsible for detecting the proper guest OS
# implementation and then delegating capabilities.
#
# Vagrant has many tasks which require specific guest OS knowledge.
# These are implemented using a guest/capability system. Various plugins
# register as "guests" which determine the underlying OS of the system.
# Then, "guest capabilities" register themselves for a specific OS (one
# or more), and these capabilities are called.
#
# Example capabilities might be "mount_virtualbox_shared_folder" or
# "configure_networks".
#
# This system allows for maximum flexibility and pluginability for doing
# guest OS specific operations.
class Guest
attr_reader :chain
# The name of the guest OS. This is available after {#detect!} is
# called.
#
# @return [Symbol]
attr_reader :name
def initialize(machine, guests, capabilities)
@logger = Log4r::Logger.new("vagrant::guest")
@capabilities = capabilities
@chain = []
@guests = guests
@machine = machine
@name = nil
end
# This will detect the proper guest OS for the machine and set up
# the class to actually execute capabilities.
def detect!
@logger.info("Detect guest for machine: #{@machine}")
# Get the mapping of guests with the most parents. We start searching
# with the guests with the most parents first.
parent_count = {}
@guests.each do |name, parts|
parent_count[name] = 0
parent = parts[1]
while parent
parent_count[name] += 1
parent = @guests[parent]
parent = parent[1] if parent
end
end
# Now swap around the mapping so that it is a mapping of
# count to the actual list of guest names
parent_count_to_guests = {}
parent_count.each do |name, count|
parent_count_to_guests[count] ||= []
parent_count_to_guests[count] << name
end
catch(:guest_os) do
sorted_counts = parent_count_to_guests.keys.sort.reverse
sorted_counts.each do |count|
parent_count_to_guests[count].each do |name|
@logger.debug("Trying: #{name}")
guest_info = @guests[name]
guest = guest_info[0].new
# If a specific guest was specified, then attempt to use that
# guest no matter what. Otherwise, only use it if it was detected.
use_this_guest = false
if @machine.config.vm.guest.nil?
use_this_guest = guest.detect?(@machine)
else
use_this_guest = @machine.config.vm.guest.to_sym == name.to_sym
end
if use_this_guest
@logger.info("Detected: #{name}!")
@chain << [name, guest]
@name = name
# Build the proper chain of parents if there are any.
# This allows us to do "inheritance" of capabilities later
if guest_info[1]
parent_name = guest_info[1]
parent_info = @guests[parent_name]
while parent_info
@chain << [parent_name, parent_info[0].new]
parent_name = parent_info[1]
parent_info = @guests[parent_name]
end
end
@logger.info("Full guest chain: #{@chain.inspect}")
# Exit the search
throw :guest_os
end
end
end
end
# We shouldn't reach this point. Ideally we would detect
# all operating systems.
raise Errors::GuestNotDetected if @chain.empty?
end
# Tests whether the guest has the named capability.
#
# @return [Boolean]
def capability?(cap_name)
!capability_module(cap_name.to_sym).nil?
end
# Executes the capability with the given name, optionally passing
# more arguments onwards to the capability.
def capability(cap_name, *args)
@logger.info("Execute capability: #{cap_name} (#{@chain[0][0]})")
cap_mod = capability_module(cap_name.to_sym)
if !cap_mod
raise Errors::GuestCapabilityNotFound,
:cap => cap_name.to_s,
:guest => @chain[0][0].to_s
end
cap_method = nil
begin
cap_method = cap_mod.method(cap_name)
rescue NameError
raise Errors::GuestCapabilityInvalid,
:cap => cap_name.to_s,
:guest => @chain[0][0].to_s
end
cap_method.call(@machine, *args)
end
# This returns whether the guest is ready to work. If this returns
# `false`, then {#detect!} should be called in order to detect the
# guest OS.
#
# @return [Boolean]
def ready?
!@chain.empty?
end
protected
# Returns the registered module for a capability with the given name.
#
# @param [Symbol] cap_name
# @return [Module]
def capability_module(cap_name)
@logger.debug("Searching for cap: #{cap_name}")
@chain.each do |guest_name, guest|
@logger.debug("Checking in: #{guest_name}")
caps = @capabilities[guest_name]
if caps && caps.has_key?(cap_name)
@logger.debug("Found cap: #{cap_name} in #{guest_name}")
return caps[cap_name]
end
end
nil
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/providers/virtualbox/action/prepare_nfs_settings.rb
|
module VagrantPlugins
module ProviderVirtualBox
module Action
class PrepareNFSSettings
def initialize(app,env)
@app = app
@logger = Log4r::Logger.new("vagrant::action::vm::nfs")
end
def call(env)
@app.call(env)
using_nfs = false
env[:machine].config.vm.synced_folders.each do |id, opts|
if opts[:nfs]
using_nfs = true
break
end
end
if using_nfs
@logger.info("Using NFS, preparing NFS settings by reading host IP and machine IP")
env[:nfs_host_ip] = read_host_ip(env[:machine])
env[:nfs_machine_ip] = read_machine_ip(env[:machine])
raise Vagrant::Errors::NFSNoHostonlyNetwork if !env[:nfs_machine_ip]
end
end
# Returns the IP address of the first host only network adapter
#
# @param [Machine] machine
# @return [String]
def read_host_ip(machine)
machine.provider.driver.read_network_interfaces.each do |adapter, opts|
if opts[:type] == :hostonly
machine.provider.driver.read_host_only_interfaces.each do |interface|
if interface[:name] == opts[:hostonly]
return interface[:ip]
end
end
end
end
nil
end
# Returns the IP address of the guest by looking at the first
# enabled host only network.
#
# @return [String]
def read_machine_ip(machine)
ips = []
machine.config.vm.networks.each do |type, options|
if type == :private_network && options[:ip].is_a?(String)
ips << options[:ip]
end
end
if ips.empty?
return nil
end
ips
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
test/unit/vagrant/plugin/v2/manager_test.rb
|
require File.expand_path("../../../../base", __FILE__)
describe Vagrant::Plugin::V2::Manager do
include_context "unit"
let(:instance) { described_class.new }
def plugin
p = Class.new(Vagrant.plugin("2"))
yield p
p
end
describe "#action_hooks" do
it "should contain globally registered hooks" do
pA = plugin do |p|
p.action_hook("foo") { "bar" }
end
pB = plugin do |p|
p.action_hook("bar") { "baz" }
end
instance.register(pA)
instance.register(pB)
result = instance.action_hooks(nil)
result.length.should == 2
result[0].call.should == "bar"
result[1].call.should == "baz"
end
it "should contain specific hooks with globally registered hooks" do
pA = plugin do |p|
p.action_hook("foo") { "bar" }
p.action_hook("foo", :foo) { "bar_foo" }
p.action_hook("foo", :bar) { "bar_bar" }
end
pB = plugin do |p|
p.action_hook("bar") { "baz" }
end
instance.register(pA)
instance.register(pB)
result = instance.action_hooks(:foo)
result.length.should == 3
result[0].call.should == "bar"
result[1].call.should == "bar_foo"
result[2].call.should == "baz"
end
end
it "should enumerate registered communicator classes" do
pA = plugin do |p|
p.communicator("foo") { "bar" }
end
pB = plugin do |p|
p.communicator("bar") { "baz" }
end
instance.register(pA)
instance.register(pB)
instance.communicators.to_hash.length.should == 2
instance.communicators[:foo].should == "bar"
instance.communicators[:bar].should == "baz"
end
it "should enumerate registered configuration classes" do
pA = plugin do |p|
p.config("foo") { "bar" }
end
pB = plugin do |p|
p.config("bar") { "baz" }
end
instance.register(pA)
instance.register(pB)
instance.config.to_hash.length.should == 2
instance.config[:foo].should == "bar"
instance.config[:bar].should == "baz"
end
it "should enumerate registered guest classes" do
pA = plugin do |p|
p.guest("foo") { "bar" }
end
pB = plugin do |p|
p.guest("bar", "foo") { "baz" }
end
instance.register(pA)
instance.register(pB)
instance.guests.to_hash.length.should == 2
instance.guests[:foo].should == ["bar", nil]
instance.guests[:bar].should == ["baz", :foo]
end
it "should enumerate registered guest capabilities" do
pA = plugin do |p|
p.guest_capability("foo", "foo") { "bar" }
end
pB = plugin do |p|
p.guest_capability("bar", "foo") { "baz" }
end
instance.register(pA)
instance.register(pB)
instance.guest_capabilities.length.should == 2
instance.guest_capabilities[:foo][:foo].should == "bar"
instance.guest_capabilities[:bar][:foo].should == "baz"
end
it "should enumerate registered host classes" do
pA = plugin do |p|
p.host("foo") { "bar" }
end
pB = plugin do |p|
p.host("bar") { "baz" }
end
instance.register(pA)
instance.register(pB)
instance.hosts.to_hash.length.should == 2
instance.hosts[:foo].should == "bar"
instance.hosts[:bar].should == "baz"
end
it "should enumerate registered provider classes" do
pA = plugin do |p|
p.provider("foo") { "bar" }
end
pB = plugin do |p|
p.provider("bar", foo: "bar") { "baz" }
end
instance.register(pA)
instance.register(pB)
instance.providers.to_hash.length.should == 2
instance.providers[:foo].should == ["bar", {}]
instance.providers[:bar].should == ["baz", { foo: "bar" }]
end
it "provides the collection of registered provider configs" do
pA = plugin do |p|
p.config("foo", :provider) { "foo" }
end
pB = plugin do |p|
p.config("bar", :provider) { "bar" }
p.config("baz") { "baz" }
end
instance.register(pA)
instance.register(pB)
instance.provider_configs.to_hash.length.should == 2
instance.provider_configs[:foo].should == "foo"
instance.provider_configs[:bar].should == "bar"
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/linux/plugin.rb
|
require "vagrant"
module VagrantPlugins
module HostLinux
class Plugin < Vagrant.plugin("2")
name "Linux host"
description "Linux host support."
host("linux") do
require File.expand_path("../host", __FILE__)
Host
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/provisioners/shell/provisioner.rb
|
require "pathname"
require "tempfile"
require "vagrant/util/downloader"
module VagrantPlugins
module Shell
class Provisioner < Vagrant.plugin("2", :provisioner)
def provision
args = ""
args = " #{config.args}" if config.args
command = "chmod +x #{config.upload_path} && #{config.upload_path}#{args}"
with_script_file do |path|
# Upload the script to the machine
@machine.communicate.tap do |comm|
# Reset upload path permissions for the current ssh user
user = @machine.ssh_info[:username]
comm.sudo("chown -R #{user} #{config.upload_path}",
:error_check => false)
comm.upload(path.to_s, config.upload_path)
if config.path
@machine.ui.info(I18n.t("vagrant.provisioners.shell.running",
script: path.to_s))
else
@machine.ui.info(I18n.t("vagrant.provisioners.shell.running",
script: "inline script"))
end
# Execute it with sudo
comm.execute(command, sudo: config.privileged) do |type, data|
if [:stderr, :stdout].include?(type)
# Output the data with the proper color based on the stream.
color = type == :stdout ? :green : :red
# Note: Be sure to chomp the data to avoid the newlines that the
# Chef outputs.
@machine.env.ui.info(
data,
:color => color, :new_line => false, :prefix => false)
end
end
end
end
end
protected
# This method yields the path to a script to upload and execute
# on the remote server. This method will properly clean up the
# script file if needed.
def with_script_file
script = nil
if config.remote?
download_path = @machine.env.tmp_path.join("#{@machine.id}-remote-script")
download_path.delete if download_path.file?
Vagrant::Util::Downloader.new(config.path, download_path).download!
script = download_path.read
download_path.delete
elsif config.path
# Just yield the path to that file...
root_path = @machine.env.root_path
script = Pathname.new(config.path).expand_path(root_path).read
else
# The script is just the inline code...
script = config.inline
end
# Replace Windows line endings with Unix ones unless binary file
script.gsub!(/\r\n?$/, "\n") if !config.binary
# Otherwise we have an inline script, we need to Tempfile it,
# and handle it specially...
file = Tempfile.new('vagrant-shell')
# Unless you set binmode, on a Windows host the shell script will
# have CRLF line endings instead of LF line endings, causing havoc
# when the guest executes it. This fixes [GH-1181].
file.binmode
begin
file.write(script)
file.fsync
file.close
yield file.path
ensure
file.close
file.unlink
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/fedora/host.rb
|
<filename>plugins/hosts/fedora/host.rb
require "pathname"
require "vagrant"
require Vagrant.source_root.join("plugins/hosts/linux/host")
module VagrantPlugins
module HostFedora
class Host < VagrantPlugins::HostLinux::Host
def self.match?
release_file = Pathname.new("/etc/redhat-release")
if release_file.exist?
release_file.open("r:ISO-8859-1:UTF-8") do |f|
contents = f.gets
return true if contents =~ /^Fedora/
return true if contents =~ /^CentOS/
return true if contents =~ /^Red Hat Enterprise Linux Server/
end
end
false
end
# Normal, mid-range precedence.
def self.precedence
5
end
def initialize(*args)
super
nfs_server_binary = "/etc/init.d/nfs"
# On Fedora 16+, systemd replaced init.d, so we have to use the
# proper NFS binary. This checks to see if we need to do that.
release_file = Pathname.new("/etc/redhat-release")
begin
release_file.open("r:ISO-8859-1:UTF-8") do |f|
version_number = /(CentOS|Fedora|Red Hat Enterprise Linux Server).*release ([0-9]+)/.match(f.gets)[2].to_i
if version_number >= 16
# "service nfs-server" will redirect properly to systemctl
# when "service nfs-server restart" is called.
nfs_server_binary = "/usr/sbin/service nfs-server"
end
end
rescue Errno::ENOENT
# File doesn't exist, not a big deal, assume we're on a
# lower version.
end
@nfs_apply_command = "/usr/sbin/exportfs -r"
@nfs_check_command = "#{nfs_server_binary} status"
@nfs_start_command = "#{nfs_server_binary} start"
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/arch/cap/configure_networks.rb
|
<reponame>camptocamp/vagrant-debian-package
require "tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins
module GuestArch
module Cap
class ConfigureNetworks
include Vagrant::Util
def self.configure_networks(machine, networks)
networks.each do |network|
entry = TemplateRenderer.render("guests/arch/network_#{network[:type]}",
:options => network)
temp = Tempfile.new("vagrant")
temp.binmode
temp.write(entry)
temp.close
machine.communicate.upload(temp.path, "/tmp/vagrant_network")
machine.communicate.sudo("ln -sf /dev/null /etc/udev/rules.d/80-net-name-slot.rules")
machine.communicate.sudo("mv /tmp/vagrant_network /etc/netctl/eth#{network[:interface]}")
machine.communicate.sudo("netctl start eth#{network[:interface]}")
end
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/action/builtin/wait_for_communicator.rb
|
<reponame>camptocamp/vagrant-debian-package
module Vagrant
module Action
module Builtin
# This waits for the communicator to be ready for a set amount of
# time.
class WaitForCommunicator
def initialize(app, env, states=nil)
@app = app
@states = states
end
def call(env)
# Wait for ready in a thread so that we can continually check
# for interrupts.
ready_thr = Thread.new do
Thread.current[:result] = env[:machine].communicate.wait_for_ready(
env[:machine].config.vm.boot_timeout)
end
# Start a thread that verifies the VM stays in a good state.
states_thr = Thread.new do
Thread.current[:result] = true
# If we aren't caring about states, just basically put this
# thread to sleep because it'll get killed later.
if !@states
while true
sleep 300
end
next
end
# Otherwise, periodically verify the VM isn't in a bad state.
while true
state = env[:machine].provider.state.id
# Used to report invalid states
Thread.current[:last_known_state] = state
# Check if we have the proper state so we can break out
if !@states.include?(state)
Thread.current[:result] = false
break
end
# Sleep a bit so we don't hit 100% CPU constantly.
sleep 1
end
end
# Wait for a result or an interrupt
env[:ui].info I18n.t("vagrant.boot_waiting")
while ready_thr.alive? && states_thr.alive?
return if env[:interrupted]
end
# If it went into a bad state, then raise an error
if !states_thr[:result]
raise Errors::VMBootBadState,
valid: @states.join(", "),
invalid: states_thr[:last_known_state]
end
# If it didn't boot, raise an error
if !ready_thr[:result]
raise Errors::VMBootTimeout
end
env[:ui].info I18n.t("vagrant.boot_completed")
# Make sure our threads are all killed
ready_thr.kill
states_thr.kill
@app.call(env)
ensure
ready_thr.kill
states_thr.kill
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/util/which.rb
|
require "vagrant/util/platform"
module Vagrant
module Util
class Which
# Cross-platform way of finding an executable in the PATH.
#
# which('ruby') #=> /usr/bin/ruby
#
# This code is adapted from the following post by mislav:
# http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby
#
# @param [String] cmd The command to search for in the PATH.
# @return [String] The full path to the executable or `nil` if not found.
def self.which(cmd)
exts = nil
if !Platform.windows? || ENV['PATHEXT'].nil?
# If the PATHEXT variable is empty, we're on *nix and need to find
# the exact filename
exts = ['']
elsif File.extname(cmd).length != 0
# On Windows: if filename contains an extension, we must match that
# exact filename
exts = ['']
else
# On Windows: otherwise try to match all possible executable file
# extensions (.EXE .COM .BAT etc.)
exts = ENV['PATHEXT'].split(';')
end
ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
exts.each do |ext|
exe = "#{path}#{File::SEPARATOR}#{cmd}#{ext}"
return exe if File.executable? exe
end
end
return nil
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/providers/virtualbox/action/export.rb
|
require "fileutils"
module VagrantPlugins
module ProviderVirtualBox
module Action
class Export
attr_reader :temp_dir
def initialize(app, env)
@app = app
end
def call(env)
@env = env
raise Vagrant::Errors::VMPowerOffToPackage if \
@env[:machine].provider.state.id != :poweroff
setup_temp_dir
export
@app.call(env)
recover(env) # called to cleanup temp directory
end
def recover(env)
if temp_dir && File.exist?(temp_dir)
FileUtils.rm_rf(temp_dir)
end
end
def setup_temp_dir
@env[:ui].info I18n.t("vagrant.actions.vm.export.create_dir")
@temp_dir = @env["export.temp_dir"] = @env[:tmp_path].join(Time.now.to_i.to_s)
FileUtils.mkpath(@env["export.temp_dir"])
end
def export
@env[:ui].info I18n.t("vagrant.actions.vm.export.exporting")
@env[:machine].provider.driver.export(ovf_path) do |progress|
@env[:ui].clear_line
@env[:ui].report_progress(progress.percent, 100, false)
end
# Clear the line a final time so the next data can appear
# alone on the line.
@env[:ui].clear_line
end
def ovf_path
File.join(@env["export.temp_dir"], "box.ovf")
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
test/unit/vagrant/action/runner_test.rb
|
<gh_stars>1-10
require File.expand_path("../../../base", __FILE__)
describe Vagrant::Action::Runner do
let(:instance) { described_class.new }
it "should raise an error if an invalid callable is given" do
expect { instance.run(7) }.to raise_error(ArgumentError, /must be a callable/)
end
it "should be able to use a Proc as a callable" do
callable = Proc.new { raise Exception, "BOOM" }
expect { instance.run(callable) }.to raise_error(Exception, "BOOM")
end
it "should be able to use a Class as a callable" do
callable = Class.new do
def initialize(app, env)
end
def call(env)
raise Exception, "BOOM"
end
end
expect { instance.run(callable) }.to raise_error(Exception, "BOOM")
end
it "should return the resulting environment" do
callable = lambda do |env|
env[:data] = "value"
# Return nil so we can make sure it isn't using this return value
nil
end
result = instance.run(callable)
result[:data].should == "value"
end
it "should pass options into hash given to callable" do
result = nil
callable = lambda do |env|
result = env["data"]
end
instance.run(callable, "data" => "foo")
result.should == "foo"
end
it "should pass global options into the hash" do
result = nil
callable = lambda do |env|
result = env["data"]
end
instance = described_class.new("data" => "bar")
instance.run(callable)
result.should == "bar"
end
it "should yield the block passed to the init method to get lazy loaded globals" do
result = nil
callable = lambda do |env|
result = env["data"]
end
instance = described_class.new { { "data" => "bar" } }
instance.run(callable)
result.should == "bar"
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/debian/cap/change_host_name.rb
|
module VagrantPlugins
module GuestDebian
module Cap
class ChangeHostName
def self.change_host_name(machine, name)
machine.communicate.tap do |comm|
# Get the current hostname
# if existing fqdn setup improperly, this returns just hostname
old = ''
comm.sudo "hostname -f" do |type, data|
if type == :stdout
old = data.chomp
end
end
# this works even if they're not both fqdn
if old.split('.')[0] != name.split('.')[0]
comm.sudo("sed -i 's/.*$/#{name.split('.')[0]}/' /etc/hostname")
# hosts should resemble:
# 127.0.1.1 host.fqdn.com host
# First to set fqdn
comm.sudo("sed -i 's@#{old}@#{name}@' /etc/hosts")
# Second to set hostname
comm.sudo("sed -i 's@#{old.split('.')[0]}@#{name.split('.')[0]}@' /etc/hosts")
comm.sudo("hostname -F /etc/hostname")
comm.sudo("hostname --fqdn > /etc/mailname")
comm.sudo("ifdown -a; ifup -a; ifup eth0")
end
end
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/hosts.rb
|
<gh_stars>1-10
require 'log4r'
module Vagrant
module Hosts
# This method detects the correct host based on the `match?` methods
# implemented in the registered hosts.
#
# @param [Hash] registry Hash mapping key to host class
def self.detect(registry)
logger = Log4r::Logger.new("vagrant::hosts")
# Sort the hosts by their precedence
host_klasses = registry.values.sort_by { |a| a.precedence }.reverse
logger.debug("Host path search classes: #{host_klasses.inspect}")
# Test for matches and return the host class that matches
host_klasses.each do |klass|
if klass.match?
logger.info("Host class: #{klass}")
return klass
end
end
# No matches found...
return nil
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/action/builtin/box_add.rb
|
<gh_stars>0
require "log4r"
require "vagrant/util/downloader"
require "vagrant/util/platform"
module Vagrant
module Action
module Builtin
# This middleware will download a remote box and add it to the
# given box collection.
class BoxAdd
def initialize(app, env)
@app = app
@logger = Log4r::Logger.new("vagrant::action::builtin::box_add")
end
def call(env)
@temp_path = env[:tmp_path].join("box" + Time.now.to_i.to_s)
@logger.info("Downloading box to: #{@temp_path}")
url = env[:box_url]
if File.file?(url) || url !~ /^[a-z0-9]+:.*$/i
@logger.info("URL is a file or protocol not found and assuming file.")
file_path = File.expand_path(url)
file_path = Util::Platform.cygwin_windows_path(file_path)
url = "file:#{file_path}"
end
downloader_options = {}
downloader_options[:insecure] = env[:box_download_insecure]
downloader_options[:ui] = env[:ui]
# Download the box to a temporary path. We store the temporary
# path as an instance variable so that the `#recover` method can
# access it.
env[:ui].info(I18n.t("vagrant.actions.box.download.downloading"))
begin
downloader = Util::Downloader.new(url, @temp_path, downloader_options)
downloader.download!
rescue Errors::DownloaderInterrupted
# The downloader was interrupted, so just return, because that
# means we were interrupted as well.
env[:ui].info(I18n.t("vagrant.actions.box.download.interrupted"))
return
end
box_formats = env[:box_provider]
if box_formats
# Determine the formats a box can support and allow the box to
# be any of those formats.
provider_plugin = Vagrant.plugin("2").manager.providers[env[:box_provider]]
if provider_plugin
box_formats = provider_plugin[1][:box_format]
box_formats ||= env[:box_provider]
end
end
# Add the box
env[:ui].info I18n.t("vagrant.actions.box.add.adding", :name => env[:box_name])
added_box = nil
begin
added_box = env[:box_collection].add(
@temp_path, env[:box_name], box_formats, env[:box_force])
rescue Vagrant::Errors::BoxUpgradeRequired
# Upgrade the box
env[:box_collection].upgrade(env[:box_name])
# Try adding it again
retry
end
# Call the 'recover' method in all cases to clean up the
# downloaded temporary file.
recover(env)
# Success, we added a box!
env[:ui].success(
I18n.t("vagrant.actions.box.add.added", name: added_box.name, provider: added_box.provider))
# Carry on!
@app.call(env)
end
def recover(env)
if @temp_path && File.exist?(@temp_path)
File.unlink(@temp_path)
end
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/solaris11/cap/mount_virtualbox_shared_folder.rb
|
<gh_stars>0
# A general Vagrant system implementation for "solaris 11".
#
# Contributed by <NAME> <<EMAIL>>
module VagrantPlugins
module GuestSolaris11
module Cap
class MountVirtualBoxSharedFolder
def self.mount_virtualbox_shared_folder(machine, name, guestpath, options)
# These are just far easier to use than the full options syntax
owner = options[:owner]
group = options[:group]
# Create the shared folder
machine.communicate.execute("#{machine.config.solaris11.suexec_cmd} mkdir -p #{guestpath}")
# We have to use this `id` command instead of `/usr/bin/id` since this
# one accepts the "-u" and "-g" flags.
id_cmd = "/usr/xpg4/bin/id"
# Mount the folder with the proper owner/group
mount_options = "-o uid=`#{id_cmd} -u #{owner}`,gid=`#{id_cmd} -g #{group}`"
if options[:mount_options]
mount_options += ",#{options[:mount_options].join(",")}"
end
machine.communicate.execute("#{machine.config.solaris11.suexec_cmd} /sbin/mount -F vboxfs #{mount_options} #{name} #{guestpath}")
# chown the folder to the proper owner/group
machine.communicate.execute("#{machine.config.solaris11.suexec_cmd} chown `#{id_cmd} -u #{owner}`:`#{id_cmd} -g #{group}` #{guestpath}")
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/plugin/v2/components.rb
|
module Vagrant
module Plugin
module V2
# This is the container class for the components of a single plugin.
# This allows us to separate the plugin class which defines the
# components, and the actual container of those components. This
# removes a bit of state overhead from the plugin class itself.
class Components
# This contains all the action hooks.
#
# @return [Hash<Symbol, Array>]
attr_reader :action_hooks
# This contains all the configuration plugins by scope.
#
# @return [Hash<Symbol, Registry>]
attr_reader :configs
# This contains all the guests and their parents.
#
# @return [Registry<Symbol, Array<Class, Symbol>>]
attr_reader :guests
# This contains all the registered guest capabilities.
#
# @return [Hash<Symbol, Registry>]
attr_reader :guest_capabilities
# This contains all the provider plugins by name, and returns
# the provider class and options.
#
# @return [Hash<Symbol, Registry>]
attr_reader :providers
def initialize
# The action hooks hash defaults to []
@action_hooks = Hash.new { |h, k| h[k] = [] }
@configs = Hash.new { |h, k| h[k] = Registry.new }
@guests = Registry.new
@guest_capabilities = Hash.new { |h, k| h[k] = Registry.new }
@providers = Registry.new
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
test/unit/vagrant/config_test.rb
|
require File.expand_path("../../base", __FILE__)
describe Vagrant::Config do
it "should not execute the proc on configuration" do
described_class.run do
raise Exception, "Failure."
end
end
it "should capture calls to `Vagrant.configure`" do
receiver = double()
procs = described_class.capture_configures do
Vagrant.configure("1") do
receiver.one
end
Vagrant.configure("2") do
receiver.two
end
end
procs.should be_kind_of(Array)
procs.length.should == 2
procs[0][0].should == "1"
procs[1][0].should == "2"
# Verify the proper procs were captured
receiver.should_receive(:one).once.ordered
receiver.should_receive(:two).once.ordered
procs[0][1].call
procs[1][1].call
end
it "should capture configuration procs" do
receiver = double()
procs = described_class.capture_configures do
described_class.run do
receiver.hello!
end
end
# Verify the structure of the result
procs.should be_kind_of(Array)
procs.length.should == 1
# Verify that the proper proc was captured
receiver.should_receive(:hello!).once
procs[0][0].should == "1"
procs[0][1].call
end
it "should capture the proper version" do
procs = described_class.capture_configures do
described_class.run("1") {}
described_class.run("2") {}
end
# Verify the structure of the result
procs.should be_kind_of(Array)
procs.length.should == 2
procs[0][0].should == "1"
procs[1][0].should == "2"
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/gentoo/host.rb
|
<reponame>camptocamp/vagrant-debian-package<filename>plugins/hosts/gentoo/host.rb
require "vagrant"
require Vagrant.source_root.join("plugins/hosts/linux/host")
module VagrantPlugins
module HostGentoo
class Host < VagrantPlugins::HostLinux::Host
def self.match?
return File.exists?("/etc/gentoo-release")
end
# Normal, mid-range precedence.
def self.precedence
5
end
def initialize(*args)
super
@nfs_apply_command = "/usr/sbin/exportfs -r"
@nfs_check_command = "service nfs status"
@nfs_start_command = "service nfs start"
end
end
end
end
|
camptocamp/vagrant-debian-package
|
test/unit/vagrant/machine_test.rb
|
require "pathname"
require File.expand_path("../../base", __FILE__)
describe Vagrant::Machine do
include_context "unit"
let(:name) { "foo" }
let(:provider) { double("provider") }
let(:provider_cls) do
obj = double("provider_cls")
obj.stub(:new => provider)
obj
end
let(:provider_config) { Object.new }
let(:provider_name) { :test }
let(:provider_options) { {} }
let(:box) { Object.new }
let(:config) { env.config_global }
let(:data_dir) { Pathname.new(Tempdir.new.path) }
let(:env) do
# We need to create a Vagrantfile so that this test environment
# has a proper root path
test_env.vagrantfile("")
# Create the Vagrant::Environment instance
test_env.create_vagrant_env
end
let(:test_env) { isolated_environment }
let(:instance) { new_instance }
subject { instance }
# Returns a new instance with the test data
def new_instance
described_class.new(name, provider_name, provider_cls, provider_config,
provider_options, config, data_dir, box, env)
end
describe "initialization" do
describe "provider initialization" do
# This is a helper that generates a test for provider intialization.
# This is a separate helper method because it takes a block that can
# be used to have additional tests on the received machine.
#
# @yield [machine] Yields the machine that the provider initialization
# method received so you can run additional tests on it.
def provider_init_test
received_machine = nil
provider_cls = double("provider_cls")
provider_cls.should_receive(:new) do |machine|
# Store this for later so we can verify that it is the
# one we expected to receive.
received_machine = machine
# Sanity check
machine.should be
# Yield our machine if we want to do additional tests
yield machine if block_given?
end
# Initialize a new machine and verify that we properly receive
# the machine we expect.
instance = described_class.new(name, provider_name, provider_cls, provider_config,
provider_options, config, data_dir, box, env)
received_machine.should eql(instance)
end
it "should initialize with the machine object" do
# Just run the blank test
provider_init_test
end
it "should have the machine name setup" do
provider_init_test do |machine|
machine.name.should == name
end
end
it "should have the machine configuration" do
provider_init_test do |machine|
machine.config.should eql(config)
end
end
it "should have the box" do
provider_init_test do |machine|
machine.box.should eql(box)
end
end
it "should have the environment" do
provider_init_test do |machine|
machine.env.should eql(env)
end
end
it "should have access to the ID" do
# Stub this because #id= calls it.
provider.stub(:machine_id_changed)
# Set the ID on the previous instance so that it is persisted
instance.id = "foo"
provider_init_test do |machine|
machine.id.should == "foo"
end
end
it "should NOT have access to the provider" do
provider_init_test do |machine|
machine.provider.should be_nil
end
end
end
end
describe "attributes" do
its(:name) { should eq(name) }
its(:config) { should eql(config) }
its(:box) { should eql(box) }
its(:env) { should eql(env) }
its(:provider) { should eql(provider) }
its(:provider_config) { should eql(provider_config) }
its(:provider_options) { should eq(provider_options) }
end
describe "actions" do
it "should be able to run an action that exists" do
action_name = :up
called = false
callable = lambda { |_env| called = true }
provider.should_receive(:action).with(action_name).and_return(callable)
instance.action(:up)
called.should be
end
it "should provide the machine in the environment" do
action_name = :up
machine = nil
callable = lambda { |env| machine = env[:machine] }
provider.stub(:action).with(action_name).and_return(callable)
instance.action(:up)
machine.should eql(instance)
end
it "should pass any extra options to the environment" do
action_name = :up
foo = nil
callable = lambda { |env| foo = env[:foo] }
provider.stub(:action).with(action_name).and_return(callable)
instance.action(:up, :foo => :bar)
foo.should == :bar
end
it "should return the environment as a result" do
action_name = :up
callable = lambda { |env| env[:result] = "FOO" }
provider.stub(:action).with(action_name).and_return(callable)
result = instance.action(action_name)
result[:result].should == "FOO"
end
it "should raise an exception if the action is not implemented" do
action_name = :up
provider.stub(:action).with(action_name).and_return(nil)
expect { instance.action(action_name) }.
to raise_error(Vagrant::Errors::UnimplementedProviderAction)
end
end
describe "communicator" do
it "should always return the SSH communicator" do
instance.communicate.should be_kind_of(VagrantPlugins::CommunicatorSSH::Communicator)
end
it "should memoize the result" do
obj = instance.communicate
instance.communicate.should eql(obj)
end
end
describe "guest implementation" do
let(:communicator) do
result = double("communicator")
result.stub(:ready?).and_return(true)
result.stub(:test).and_return(false)
result
end
before(:each) do
test_guest = Class.new(Vagrant.plugin("2", :guest)) do
def detect?(machine)
true
end
end
register_plugin do |p|
p.guest(:test) { test_guest }
end
instance.stub(:communicate).and_return(communicator)
end
it "should raise an exception if communication is not ready" do
communicator.should_receive(:ready?).and_return(false)
expect { instance.guest }.
to raise_error(Vagrant::Errors::MachineGuestNotReady)
end
it "should return the configured guest" do
result = instance.guest
result.should be_kind_of(Vagrant::Guest)
result.ready?.should be
result.chain[0][0].should == :test
end
end
describe "setting the ID" do
before(:each) do
provider.stub(:machine_id_changed)
end
it "should not have an ID by default" do
instance.id.should be_nil
end
it "should set an ID" do
instance.id = "bar"
instance.id.should == "bar"
end
it "should notify the machine that the ID changed" do
provider.should_receive(:machine_id_changed).once
instance.id = "bar"
end
it "should persist the ID" do
instance.id = "foo"
new_instance.id.should == "foo"
end
it "should delete the ID" do
instance.id = "foo"
second = new_instance
second.id.should == "foo"
second.id = nil
third = new_instance
third.id.should be_nil
end
end
describe "ssh info" do
describe "with the provider returning nil" do
it "should return nil if the provider returns nil" do
provider.should_receive(:ssh_info).and_return(nil)
instance.ssh_info.should be_nil
end
end
describe "with the provider returning data" do
let(:provider_ssh_info) { {} }
before(:each) do
provider.should_receive(:ssh_info).and_return(provider_ssh_info)
end
[:host, :port, :username].each do |type|
it "should return the provider data if not configured in Vagrantfile" do
provider_ssh_info[type] = "foo"
instance.config.ssh.send("#{type}=", nil)
instance.ssh_info[type].should == "foo"
end
it "should return the Vagrantfile value if provider data not given" do
provider_ssh_info[type] = nil
instance.config.ssh.send("#{type}=", "bar")
instance.ssh_info[type].should == "bar"
end
it "should use the default if no override and no provider" do
provider_ssh_info[type] = nil
instance.config.ssh.send("#{type}=", nil)
instance.config.ssh.default.send("#{type}=", "foo")
instance.ssh_info[type].should == "foo"
end
it "should use the override if set even with a provider" do
provider_ssh_info[type] = "baz"
instance.config.ssh.send("#{type}=", "bar")
instance.config.ssh.default.send("#{type}=", "foo")
instance.ssh_info[type].should == "bar"
end
end
it "should set the configured forward agent settings" do
provider_ssh_info[:forward_agent] = true
instance.config.ssh.forward_agent = false
instance.ssh_info[:forward_agent].should == false
end
it "should set the configured forward X11 settings" do
provider_ssh_info[:forward_x11] = true
instance.config.ssh.forward_x11 = false
instance.ssh_info[:forward_x11].should == false
end
it "should return the provider private key if given" do
provider_ssh_info[:private_key_path] = "/foo"
instance.ssh_info[:private_key_path].should == "/foo"
end
it "should return the configured SSH key path if set" do
provider_ssh_info[:private_key_path] = nil
instance.config.ssh.private_key_path = "/bar"
instance.ssh_info[:private_key_path].should == "/bar"
end
context "expanding path relative to the root path" do
it "should with the provider key path" do
provider_ssh_info[:private_key_path] = "~/foo"
instance.ssh_info[:private_key_path].should ==
File.expand_path("~/foo", env.root_path)
end
it "should with the config private key path" do
provider_ssh_info[:private_key_path] = nil
instance.config.ssh.private_key_path = "~/bar"
instance.ssh_info[:private_key_path].should ==
File.expand_path("~/bar", env.root_path)
end
end
it "should return the default private key path if provider and config doesn't have one" do
provider_ssh_info[:private_key_path] = nil
instance.config.ssh.private_key_path = nil
instance.ssh_info[:private_key_path].should == instance.env.default_private_key_path.to_s
end
end
end
describe "state" do
it "should query state from the provider" do
state = Vagrant::MachineState.new(:id, "short", "long")
provider.should_receive(:state).and_return(state)
instance.state.id.should == :id
end
it "should raise an exception if a MachineState is not returned" do
provider.should_receive(:state).and_return(:old_school)
expect { instance.state }.
to raise_error(Vagrant::Errors::MachineStateInvalid)
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/commands/help/command.rb
|
require 'optparse'
module VagrantPlugins
module CommandHelp
class Command < Vagrant.plugin("2", :command)
def execute
return @env.cli([]) if @argv.empty?
@env.cli([@argv[0], "-h"])
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/commands/destroy/command.rb
|
module VagrantPlugins
module CommandDestroy
class Command < Vagrant.plugin("2", :command)
def execute
options = {}
options[:force] = false
opts = OptionParser.new do |o|
o.banner = "Usage: vagrant destroy [vm-name]"
o.separator ""
o.on("-f", "--force", "Destroy without confirmation.") do |f|
options[:force] = f
end
end
# Parse the options
argv = parse_options(opts)
return if !argv
@logger.debug("'Destroy' each target VM...")
declined = false
with_target_vms(argv, :reverse => true) do |vm|
action_env = vm.action(
:destroy, :force_confirm_destroy => options[:force])
declined = true if action_env.has_key?(:force_confirm_destroy_result) &&
action_env[:force_confirm_destroy_result] == false
end
# Success if no confirms were declined
declined ? 1 : 0
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/kernel_v2/config/vagrant.rb
|
require "vagrant"
module VagrantPlugins
module Kernel_V2
class VagrantConfig < Vagrant.plugin("2", :config)
attr_accessor :host
def to_s
"Vagrant"
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/action/builtin/provision.rb
|
<reponame>camptocamp/vagrant-debian-package<filename>lib/vagrant/action/builtin/provision.rb<gh_stars>0
require "log4r"
require_relative "mixin_provisioners"
module Vagrant
module Action
module Builtin
# This class will run the configured provisioners against the
# machine.
#
# This action should be placed BEFORE the machine is booted so it
# can do some setup, and then run again (on the return path) against
# a running machine.
class Provision
include MixinProvisioners
def initialize(app, env)
@app = app
@logger = Log4r::Logger.new("vagrant::action::builtin::provision")
end
def call(env)
@env = env
# Check if we're even provisioning things.
enabled = true
# Check if we already provisioned, and if so, disable the rest
ignore_sentinel = true
ignore_sentinel = env[:provision_ignore_sentinel] if env.has_key?(:provision_ignore_sentinel)
if !ignore_sentinel
@logger.info("Checking provisioner sentinel if we should run...")
sentinel = env[:machine].data_dir.join("action_provision")
if sentinel.file?
@logger.info("Sentinel found! Not provisioning.")
enabled = false
else
@logger.info("Sentinel not found.")
sentinel.open("w") do |f|
f.write(Time.now.to_i.to_s)
end
end
end
# If we explicitly specified, take that value.
enabled = env[:provision_enabled] if env.has_key?(:provision_enabled)
# Ask the provisioners to modify the configuration if needed
provisioner_instances.each do |p|
p.configure(env[:machine].config)
end
# Continue, we need the VM to be booted.
@app.call(env)
# Actually provision if we enabled it
if enabled
provisioner_instances.each do |p|
next if env[:provision_types] && \
!env[:provision_types].include?(provisioner_type_map[p])
run_provisioner(env, provisioner_type_map[p].to_s, p)
end
end
end
# This is pulled out into a seperate method so that users can
# subclass and implement custom behavior if they'd like around
# this step.
def run_provisioner(env, name, p)
env[:ui].info(I18n.t("vagrant.actions.vm.provision.beginning",
:provisioner => name))
p.provision
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/util/downloader.rb
|
<gh_stars>0
require "log4r"
require "vagrant/util/busy"
require "vagrant/util/subprocess"
module Vagrant
module Util
# This class downloads files using various protocols by subprocessing
# to cURL. cURL is a much more capable and complete download tool than
# a hand-rolled Ruby library, so we defer to its expertise.
class Downloader
# Custom user agent provided to cURL so that requests to URL shorteners
# are properly tracked.
USER_AGENT = "Vagrant/#{VERSION}"
def initialize(source, destination, options=nil)
@logger = Log4r::Logger.new("vagrant::util::downloader")
@source = source.to_s
@destination = destination.to_s
# Get the various optional values
options ||= {}
@insecure = options[:insecure]
@ui = options[:ui]
end
# This executes the actual download, downloading the source file
# to the destination with the given options used to initialize this
# class.
#
# If this method returns without an exception, the download
# succeeded. An exception will be raised if the download failed.
def download!
# Build the list of parameters to execute with cURL
options = [
"--fail",
"--location",
"--max-redirs", "10",
"--user-agent", USER_AGENT,
"--output", @destination
]
options << "--insecure" if @insecure
options << @source
# Specify some options for the subprocess
subprocess_options = {}
# If we're in Vagrant, then we use the packaged CA bundle
if Vagrant.in_installer?
subprocess_options[:env] ||= {}
subprocess_options[:env]["CURL_CA_BUNDLE"] =
File.expand_path("cacert.pem", ENV["VAGRANT_INSTALLER_EMBEDDED_DIR"])
end
# This variable can contain the proc that'll be sent to
# the subprocess execute.
data_proc = nil
if @ui
# If we're outputting progress, then setup the subprocess to
# tell us output so we can parse it out.
subprocess_options[:notify] = :stderr
progress_data = ""
progress_regexp = /(\r(.+?))\r/
# Setup the proc that'll receive the real-time data from
# the downloader.
data_proc = Proc.new do |type, data|
# Type will always be "stderr" because that is the only
# type of data we're subscribed for notifications.
# Accumulate progress_data
progress_data << data
while true
# If we have a full amount of column data (two "\r") then
# we report new progress reports. Otherwise, just keep
# accumulating.
match = progress_regexp.match(progress_data)
break if !match
data = match[2]
progress_data.gsub!(match[1], "")
# Ignore the first \r and split by whitespace to grab the columns
columns = data.strip.split(/\s+/)
# COLUMN DATA:
#
# 0 - % total
# 1 - Total size
# 2 - % received
# 3 - Received size
# 4 - % transferred
# 5 - Transferred size
# 6 - Average download speed
# 7 - Average upload speed
# 9 - Total time
# 9 - Time spent
# 10 - Time left
# 11 - Current speed
output = "Progress: #{columns[0]}% (Rate: #{columns[11]}/s, Estimated time remaining: #{columns[10]})"
@ui.clear_line
@ui.info(output, :new_line => false)
end
end
end
# Add the subprocess options onto the options we'll execute with
options << subprocess_options
# Create the callback that is called if we are interrupted
interrupted = false
int_callback = Proc.new do
@logger.info("Downloader interrupted!")
interrupted = true
end
@logger.info("Downloader starting download: ")
@logger.info(" -- Source: #{@source}")
@logger.info(" -- Destination: #{@destination}")
# Execute!
result = Busy.busy(int_callback) do
Subprocess.execute("curl", *options, &data_proc)
end
# If the download was interrupted, then raise a specific error
raise Errors::DownloaderInterrupted if interrupted
# If we're outputting to the UI, clear the output to
# avoid lingering progress meters.
@ui.clear_line if @ui
# If it didn't exit successfully, we need to parse the data and
# show an error message.
if result.exit_code != 0
@logger.warn("Downloader exit code: #{result.exit_code}")
parts = result.stderr.split(/\n*curl:\s+\(\d+\)\s*/, 2)
parts[1] ||= ""
raise Errors::DownloaderError, :message => parts[1].chomp
end
# Everything succeeded
true
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/ubuntu/cap/mount_nfs.rb
|
<gh_stars>1-10
require Vagrant.source_root.join("plugins/guests/linux/cap/mount_nfs")
module VagrantPlugins
module GuestUbuntu
module Cap
class MountNFS < GuestLinux::Cap::MountNFS
def self.mount_nfs_folder(machine, ip, folders)
super
# Emit an upstart events if upstart is available
folders.each do |name, opts|
real_guestpath = machine.guest.capability(:shell_expand_guest_path, opts[:guestpath])
machine.communicate.sudo("[ -x /sbin/initctl ] && /sbin/initctl emit vagrant-mounted MOUNTPOINT=#{real_guestpath}")
end
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/slackware/host.rb
|
<filename>plugins/hosts/slackware/host.rb<gh_stars>1-10
require "vagrant"
require Vagrant.source_root.join("plugins/hosts/linux/host")
module VagrantPlugins
module HostSlackware
class Host < VagrantPlugins::HostLinux::Host
def self.match?
return File.exists?("/etc/slackware-release") || Dir.glob("/usr/lib/setup/Plamo-*").length > 0
end
# Normal, mid-range precedence.
def self.precedence
5
end
def initialize(*args)
super
@nfs_apply_command = "/usr/sbin/exportfs -r"
@nfs_check_command = "pidof nfsd > /dev/null"
@nfs_start_command = "/etc/rc.d/rc.nfsd start"
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/ubuntu/cap/mount_virtualbox_shared_folder.rb
|
<reponame>camptocamp/vagrant-debian-package<gh_stars>0
require Vagrant.source_root.join("plugins/guests/linux/cap/mount_virtualbox_shared_folder")
module VagrantPlugins
module GuestUbuntu
module Cap
class MountVirtualBoxSharedFolder < GuestLinux::Cap::MountVirtualBoxSharedFolder
def self.mount_virtualbox_shared_folder(machine, name, guestpath, options)
super
machine.communicate.sudo("[ -x /sbin/initctl ] && /sbin/initctl emit vagrant-mounted MOUNTPOINT=#{guestpath}")
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/commands/plugin/action/bundler_check.rb
|
<gh_stars>1-10
module VagrantPlugins
module CommandPlugin
module Action
class BundlerCheck
def initialize(app, env)
@app = app
end
def call(env)
# Bundler sets up its own custom gem load paths such that our
# own gems are never loaded. Therefore, give an error if a user
# tries to install gems while within a Bundler-managed environment.
if defined?(Bundler)
require 'bundler/shared_helpers'
if Bundler::SharedHelpers.in_bundle?
raise Vagrant::Errors::GemCommandInBundler
end
end
@app.call(env)
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/action/builtin/ssh_run.rb
|
require "log4r"
module Vagrant
module Action
module Builtin
# This class will run a single command on the remote machine and will
# mirror the output to the UI. The resulting exit status of the command
# will exist in the `:ssh_run_exit_status` key in the environment.
class SSHRun
def initialize(app, env)
@app = app
@logger = Log4r::Logger.new("vagrant::action::builtin::ssh_run")
end
def call(env)
command = env[:ssh_run_command]
@logger.debug("Executing command: #{command}")
exit_status = 0
exit_status = env[:machine].communicate.execute(command, :error_check => false) do |type, data|
# Determine the proper channel to send the output onto depending
# on the type of data we are receiving.
channel = type == :stdout ? :out : :error
# Print the output as it comes in, but don't prefix it and don't
# force a new line so that the output is properly preserved however
# it may be formatted.
env[:ui].info(data.to_s,
:prefix => false,
:new_line => false,
:channel => channel)
end
# Set the exit status on a known environmental variable
env[:ssh_run_exit_status] = exit_status
# Call the next middleware
@app.call(env)
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/kernel_v2/config/nfs.rb
|
require "vagrant"
module VagrantPlugins
module Kernel_V2
class NFSConfig < Vagrant.plugin("2", :config)
attr_accessor :map_uid
attr_accessor :map_gid
def to_s
"NFS"
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/commands/plugin/command/base.rb
|
module VagrantPlugins
module CommandPlugin
module Command
class Base < Vagrant.plugin("2", :command)
# This is a helper for executing an action sequence with the proper
# environment hash setup so that the plugin specific helpers are
# in.
#
# @param [Object] callable the Middleware callable
# @param [Hash] env Extra environment hash that is merged in.
def action(callable, env=nil)
env = {
:gem_helper => GemHelper.new(@env.gems_path),
:plugin_state_file => StateFile.new(@env.home_path.join("plugins.json"))
}.merge(env || {})
@env.action_runner.run(callable, env)
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/bsd/plugin.rb
|
<reponame>camptocamp/vagrant-debian-package
require "vagrant"
module VagrantPlugins
module HostBSD
class Plugin < Vagrant.plugin("2")
name "BSD host"
description "BSD host support."
host("bsd") do
require File.expand_path("../host", __FILE__)
Host
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/plugin.rb
|
<filename>lib/vagrant/plugin.rb
module Vagrant
module Plugin
autoload :V1, "vagrant/plugin/v1"
autoload :V2, "vagrant/plugin/v2"
end
end
|
camptocamp/vagrant-debian-package
|
plugins/commands/plugin/plugin.rb
|
<filename>plugins/commands/plugin/plugin.rb
require "vagrant"
module VagrantPlugins
module CommandPlugin
class Plugin < Vagrant.plugin("2")
name "plugin command"
description <<-DESC
This command helps manage and install plugins within the
Vagrant environment.
DESC
command("plugin") do
require File.expand_path("../command/root", __FILE__)
Command::Root
end
end
autoload :Action, File.expand_path("../action", __FILE__)
autoload :GemHelper, File.expand_path("../gem_helper", __FILE__)
autoload :StateFile, File.expand_path("../state_file", __FILE__)
end
end
|
camptocamp/vagrant-debian-package
|
plugins/providers/virtualbox/action/set_name.rb
|
require "log4r"
module VagrantPlugins
module ProviderVirtualBox
module Action
class SetName
def initialize(app, env)
@logger = Log4r::Logger.new("vagrant::action::vm::setname")
@app = app
end
def call(env)
name = env[:machine].provider_config.name
# If we already set the name before, then don't do anything
sentinel = env[:machine].data_dir.join("action_set_name")
if !name && sentinel.file?
@logger.info("Default name was already set before, not doing it again.")
return @app.call(env)
end
# If no name was manually set, then use a default
if !name
prefix = "#{env[:root_path].basename.to_s}_#{env[:machine].name}"
prefix.gsub!(/[^-a-z0-9_]/i, "")
name = prefix + "_#{Time.now.to_i}"
end
# Verify the name is not taken
vms = env[:machine].provider.driver.read_vms
raise Vagrant::Errors::VMNameExists, :name => name if \
vms.has_key?(name) && vms[name] != env[:machine].id
if vms.has_key?(name)
@logger.info("Not setting the name because our name is already set.")
else
@logger.info("Setting the name of the VM: #{name}")
env[:ui].info(I18n.t("vagrant.actions.vm.set_name.setting_name"))
env[:machine].provider.driver.set_name(name)
end
# Create the sentinel
sentinel.open("w") do |f|
f.write(Time.now.to_i.to_s)
end
@app.call(env)
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/arch/host.rb
|
require "vagrant"
require Vagrant.source_root.join("plugins/hosts/linux/host")
module VagrantPlugins
module HostArch
class Host < VagrantPlugins::HostLinux::Host
def self.match?
File.exist?("/etc/arch-release")
end
def self.nfs?
# HostLinux checks for nfsd which returns false unless the
# services are actively started. This leads to a misleading
# error message. Checking for nfs (no d) seems to work
# regardless. Also fixes useless use of cat, regex, and
# redirection.
Kernel.system("grep -Fq nfs /proc/filesystems")
end
# Normal, mid-range precedence.
def self.precedence
5
end
def initialize(*args)
super
if systemd?
@nfs_check_command = "/usr/sbin/systemctl status nfsd"
@nfs_start_command = "/usr/sbin/systemctl start nfsd rpc-idmapd rpc-mountd rpcbind"
else
@nfs_check_command = "/etc/rc.d/nfs-server status"
@nfs_start_command = "sh -c 'for s in {rpcbind,nfs-common,nfs-server}; do /etc/rc.d/$s start; done'"
end
end
protected
# This tests to see if systemd is used on the system. This is used
# in newer versions of Arch, and requires a change in behavior.
def systemd?
`ps -o comm= 1`.chomp == 'systemd'
end
end
end
end
|
camptocamp/vagrant-debian-package
|
test/unit/base.rb
|
<reponame>camptocamp/vagrant-debian-package
require "rubygems"
require "rspec/autorun"
# Require Vagrant itself so we can reference the proper
# classes to test.
require "vagrant"
# Add the test directory to the load path
$:.unshift File.expand_path("../../", __FILE__)
# Load in helpers
require "support/tempdir"
require "unit/support/dummy_provider"
require "unit/support/shared/base_context"
# Do not buffer output
$stdout.sync = true
$stderr.sync = true
# Configure RSpec
RSpec.configure do |c|
c.expect_with :rspec, :stdlib
end
# Configure VAGRANT_CWD so that the tests never find an actual
# Vagrantfile anywhere, or at least this minimizes those chances.
ENV["VAGRANT_CWD"] = Tempdir.new.path
|
camptocamp/vagrant-debian-package
|
plugins/provisioners/puppet/config/puppet_server.rb
|
module VagrantPlugins
module Puppet
module Config
class PuppetServer < Vagrant.plugin("2", :config)
attr_accessor :puppet_server
attr_accessor :puppet_node
attr_accessor :options
attr_accessor :facter
def facter; @facter ||= {}; end
def puppet_server; @puppet_server || "puppet"; end
def options; @options ||= []; end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
lib/vagrant/plugin/v2/host.rb
|
module Vagrant
module Plugin
module V2
# Base class for a host in Vagrant. A host class contains functionality
# that is specific to a specific OS that is running Vagrant. This
# abstraction is done becauase there is some host-specific logic that
# Vagrant must do in some cases.
class Host
# This returns true/false depending on if the current running system
# matches the host class.
#
# @return [Boolean]
def self.match?
nil
end
# The precedence of the host when checking for matches. This is to
# allow certain host such as generic OS's ("Linux", "BSD", etc.)
# to be specified last.
#
# The hosts with the higher numbers will be checked first.
#
# If you're implementing a basic host, you can probably ignore this.
def self.precedence
5
end
# Initializes a new host class.
#
# The only required parameter is a UI object so that the host
# objects have some way to communicate with the outside world.
#
# @param [UI] ui UI for the hosts to output to.
def initialize(ui)
@ui = ui
end
# Returns true of false denoting whether or not this host supports
# NFS shared folder setup. This method ideally should verify that
# NFS is installed.
#
# @return [Boolean]
def nfs?
false
end
# Exports the given hash of folders via NFS.
#
# @param [String] id A unique ID that is guaranteed to be unique to
# match these sets of folders.
# @param [String] ip IP of the guest machine.
# @param [Hash] folders Shared folders to sync.
def nfs_export(id, ip, folders)
end
# Prunes any NFS exports made by Vagrant which aren't in the set
# of valid ids given.
#
# @param [Array<String>] valid_ids Valid IDs that should not be
# pruned.
def nfs_prune(valid_ids)
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/provisioners/salt/errors.rb
|
<filename>plugins/provisioners/salt/errors.rb
require "vagrant"
module VagrantPlugins
module Salt
module Errors
class SaltError < Vagrant::Errors::VagrantError
error_namespace("salt")
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/freebsd/cap/configure_networks.rb
|
require "tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins
module GuestFreeBSD
module Cap
class ConfigureNetworks
include Vagrant::Util
def self.configure_networks(machine, networks)
# Remove any previous network additions to the configuration file.
machine.communicate.sudo("sed -i '' -e '/^#VAGRANT-BEGIN/,/^#VAGRANT-END/ d' /etc/rc.conf")
networks.each do |network|
entry = TemplateRenderer.render("guests/freebsd/network_#{network[:type]}",
:options => network)
# Write the entry to a temporary location
temp = Tempfile.new("vagrant")
temp.binmode
temp.write(entry)
temp.close
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry")
machine.communicate.sudo("su -m root -c 'cat /tmp/vagrant-network-entry >> /etc/rc.conf'")
machine.communicate.sudo("rm /tmp/vagrant-network-entry")
if network[:type].to_sym == :static
machine.communicate.sudo("ifconfig em#{network[:interface]} inet #{network[:ip]} netmask #{network[:netmask]}")
elsif network[:type].to_sym == :dhcp
machine.communicate.sudo("dhclient em#{network[:interface]}")
end
end
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/opensuse/plugin.rb
|
require "vagrant"
module VagrantPlugins
module HostOpenSUSE
class Plugin < Vagrant.plugin("2")
name "OpenSUSE host"
description "OpenSUSE host support."
host("opensuse") do
require File.expand_path("../host", __FILE__)
Host
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/hosts/slackware/plugin.rb
|
require "vagrant"
module VagrantPlugins
module HostSlackware
class Plugin < Vagrant.plugin("2")
name "Slackware host"
description "Slackware and derivertives host support."
host("slackware") do
require File.expand_path("../host", __FILE__)
Host
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/commands/box/command/remove.rb
|
require 'optparse'
module VagrantPlugins
module CommandBox
module Command
class Remove < Vagrant.plugin("2", :command)
def execute
opts = OptionParser.new do |o|
o.banner = "Usage: vagrant box remove <name> <provider>"
end
# Parse the options
argv = parse_options(opts)
return if !argv
raise Vagrant::Errors::CLIInvalidUsage, :help => opts.help.chomp if argv.length < 1
if !argv[1]
# Try to automatically determine the provider.
providers = []
@env.boxes.all.each do |name, provider|
if name == argv[0]
providers << provider
end
end
if providers.length > 1
@env.ui.error(
I18n.t("vagrant.commands.box.remove_must_specify_provider",
name: argv[0],
providers: providers.join(", ")))
return 1
end
argv[1] = providers[0] || ""
end
b = nil
begin
b = @env.boxes.find(argv[0], argv[1].to_sym)
rescue Vagrant::Errors::BoxUpgradeRequired
@env.boxes.upgrade(argv[0])
retry
end
raise Vagrant::Errors::BoxNotFound, :name => argv[0], :provider => argv[1].to_sym if !b
@env.ui.info(I18n.t("vagrant.commands.box.removing",
:name => argv[0],
:provider => argv[1]))
b.destroy!
# Success, exit status 0
0
end
end
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/freebsd/guest.rb
|
<gh_stars>1-10
require 'vagrant/util/template_renderer'
module VagrantPlugins
module GuestFreeBSD
# A general Vagrant system implementation for "freebsd".
#
# Contributed by <NAME> <<EMAIL>>
class Guest < Vagrant.plugin("2", :guest)
def detect?(machine)
machine.communicate.test("uname -s | grep 'FreeBSD'")
end
end
end
end
|
camptocamp/vagrant-debian-package
|
test/unit/vagrant/plugin/v2/components_test.rb
|
require File.expand_path("../../../../base", __FILE__)
require "vagrant/registry"
describe Vagrant::Plugin::V2::Components do
let(:instance) { described_class.new }
describe "configs" do
it "should have configs" do
instance.configs.should be_kind_of(Hash)
end
it "should default the values to registries" do
instance.configs[:i_probably_dont_exist].should be_kind_of(Vagrant::Registry)
end
end
end
|
camptocamp/vagrant-debian-package
|
plugins/guests/debian/plugin.rb
|
require "vagrant"
module VagrantPlugins
module GuestDebian
class Plugin < Vagrant.plugin("2")
name "Debian guest"
description "Debian guest support."
guest("debian", "linux") do
require File.expand_path("../guest", __FILE__)
Guest
end
guest_capability("debian", "configure_networks") do
require_relative "cap/configure_networks"
Cap::ConfigureNetworks
end
guest_capability("debian", "change_host_name") do
require_relative "cap/change_host_name"
Cap::ChangeHostName
end
end
end
end
|
RiotGames/unicorn
|
definitions/unicorn_config.rb
|
<reponame>RiotGames/unicorn<gh_stars>1-10
#
# Author:: <NAME> <<EMAIL>>
# Cookbook Name:: unicorn
# Definition:: unicorn_config
#
# Copyright 2009, Opscode, Inc.
#
# 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.
#
define :unicorn_config, :listen => nil, :working_directory => nil, :worker_timeout => 60, :preload_app => false, :worker_processes => 4, :before_fork => nil, :after_fork => nil, :pid => nil, :stderr_path => nil, :stdout_path => nil, :notifies => nil, :owner => nil, :group => nil, :mode => nil do
config_dir = File.dirname(params[:name])
directory config_dir do
recursive true
action :create
end
params[:listen] = {params[:listen] => {}} if params[:listen].kind_of? String or params[:listen].kind_of? Integer
tvars = params.clone
params[:listen].each do |port, options|
oarray = Array.new
options.each do |k, v|
oarray << ":#{k} => #{v}"
end
tvars[:listen][port] = oarray.join(", ")
end
template params[:name] do
source "unicorn.rb.erb"
cookbook "unicorn"
mode "0644"
owner params[:owner] if params[:owner]
group params[:group] if params[:group]
mode params[:mode] if params[:mode]
variables params
notifies *params[:notifies] if params[:notifies]
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/actions/input_action.rb
|
<filename>lib/formtastic/actions/input_action.rb
module Formtastic
module Actions
# Outputs an `<input type="submit">` or `<input type="reset">` wrapped in the standard `<li>`
# wrapper. This the default for `:submit` and `:reset` actions, but `:as => :button` is also
# available as an alternative.
#
# @example The `:as` can be ommitted, these are functionally equivalent
# <%= f.action :submit, :as => :input %>
# <%= f.action :submit %>
#
# @example Full form context and output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.actions do %>
# <%= f.action :reset, :as => :input %>
# <%= f.action :submit, :as => :input %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset class="actions">
# <ol>
# <li class="action input_action" id="post_reset_action">
# <input type="reset" value="Reset">
# </li>
# <li class="action input_action" id="post_submit_action">
# <input type="submit" value="Create Post">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @example Specifying a label with a String
# <%= f.action :submit, :as => :input, :label => "Go" %>
#
# @example Pass HTML attributes down to the `<input>`
# <%= f.action :submit, :as => :input, :button_html => { :class => 'pretty', :accesskey => 'g', :disable_with => "Wait..." } %>
#
# @example Access key can also be set as a top-level option
# <%= f.action :submit, :as => :input, :accesskey => 'g' %>
#
# @example Pass HTML attributes down to the `<li>` wrapper (classes are appended to the existing classes)
# <%= f.action :submit, :as => :input, :wrapper_html => { :class => 'special', :id => 'whatever' } %>
# <%= f.action :submit, :as => :input, :wrapper_html => { :class => ['extra', 'special'], :id => 'whatever' } %>
# @todo document i18n keys
# @todo document i18n translation with :label (?)
class InputAction
include Base
include Buttonish
# @see Formtastic::Helpers::ActionHelper#action
# @option *args :label [String, Symbol]
# Override the label text with a String or a symbol for an i18n translation key
#
# @option *args :button_html [Hash]
# Override or add to the HTML attributes to be passed down to the `<input>` tag
#
# @option *args :wrapper_html [Hash]
# Override or add to the HTML attributes to be passed down to the wrapping `<li>` tag
#
def to_html
wrapper do
builder.submit(text, button_html)
end
end
end
end
end
|
ryanfox1985/formtastic
|
spec/util_spec.rb
|
<reponame>ryanfox1985/formtastic
# encoding: utf-8
require 'spec_helper'
RSpec.describe 'Formtastic::Util' do
describe '.deprecated_version_of_rails?' do
subject { Formtastic::Util.deprecated_version_of_rails? }
context '4.1.0' do
before { allow(Formtastic::Util).to receive(:rails_version) { "4.1.0" } }
it 'should be false' do
expect(subject).to be_falsey
end
end
context '4.1.1' do
before { allow(Formtastic::Util).to receive(:rails_version) { "4.1.1" } }
it 'should be false' do
expect(subject).to be_falsey
end
end
context '4.2.0' do
before { allow(Formtastic::Util).to receive(:rails_version) { "4.2.0" } }
it 'should be false' do
expect(subject).to be_falsey
end
end
context '5.0.0' do
before { allow(Formtastic::Util).to receive(:rails_version) { "5.0.0" } }
it 'should be true' do
expect(subject).to be_falsey
end
end
end
end
|
ryanfox1985/formtastic
|
spec/inputs/with_options_spec.rb
|
# encoding: utf-8
require 'spec_helper'
RSpec.describe 'string input' do
include FormtasticSpecHelper
before do
@output_buffer = ''
mock_everything
end
describe "with_options and :wrapper_html" do
before do
concat(semantic_form_for(@new_post) do |builder|
builder.with_options :wrapper_html => { :class => ['extra'] } do |opt_builder|
concat(opt_builder.input(:title, :as => :string))
concat(opt_builder.input(:author, :as => :radio))
end
end)
end
it "should have extra class on title" do
expect(output_buffer).to have_tag("form li#post_title_input.extra")
end
it "should have title as string" do
expect(output_buffer).to have_tag("form li#post_title_input.string")
end
it "should not have title as radio" do
expect(output_buffer).not_to have_tag("form li#post_title_input.radio")
end
it "should have extra class on author" do
expect(output_buffer).to have_tag("form li#post_author_input.extra")
end
it "should not have author as string" do
expect(output_buffer).not_to have_tag("form li#post_author_input.string")
end
it "should have author as radio" do
expect(output_buffer).to have_tag("form li#post_author_input.radio")
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/deprecation.rb
|
<filename>lib/formtastic/deprecation.rb
require 'active_support/deprecation'
module Formtastic
Deprecation = ActiveSupport::Deprecation
end
|
ryanfox1985/formtastic
|
lib/formtastic/actions/buttonish.rb
|
module Formtastic
module Actions
module Buttonish
def supported_methods
[:submit, :reset]
end
def extra_button_html_options
{
:type => method
}
end
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/inputs/base/datetime_pickerish.rb
|
module Formtastic
module Inputs
module Base
module DatetimePickerish
include Base::Placeholder
def html_input_type
raise NotImplementedError
end
def default_size
raise NotImplementedError
end
def value
raise NotImplementedError
end
def input_html_options
super.merge(extra_input_html_options)
end
def extra_input_html_options
{
:type => html_input_type,
:size => size,
:maxlength => maxlength,
:step => step,
:value => value
}
end
def size
return options[:size] if options.key?(:size)
return options[:input_html][:size] if options[:input_html] && options[:input_html].key?(:size)
default_size
end
def step
return step_from_macro(options[:input_html][:step]) if options[:input_html] && options[:input_html][:step] && options[:input_html][:step].is_a?(Symbol)
return options[:input_html][:step] if options[:input_html] && options[:input_html].key?(:step)
default_step
end
def maxlength
return options[:maxlength] if options.key?(:maxlength)
return options[:input_html][:maxlength] if options[:input_html] && options[:input_html].key?(:maxlength)
default_size
end
def default_maxlength
default_size
end
def default_step
1
end
protected
def step_from_macro(sym)
case sym
# date
when :day then "1"
when :seven_days, :week then "7"
when :two_weeks, :fortnight then "14"
when :four_weeks then "28"
when :thirty_days then "30"
# time
when :second then "1"
when :minute then "60"
when :fifteen_minutes, :quarter_hour then "900"
when :thirty_minutes, :half_hour then "1800"
when :sixty_minutes, :hour then "3600"
else sym
end
end
end
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/inputs/date_select_input.rb
|
module Formtastic
module Inputs
# Outputs a series of select boxes for the fragments that make up a date (year, month, day).
#
# @see Formtastic::Inputs::Base::Timeish Timeish module for documentation of date, time and datetime input options.
class DateSelectInput
include Base
include Base::Timeish
# We don't want hour and minute fragments on a date input
def time_fragments
[]
end
def hidden_date_fragments
default_date_fragments - date_fragments
end
def hidden_fragments
hidden_date_fragments.map do |fragment|
template.hidden_field_tag(hidden_field_name(fragment), fragment_value(fragment), :id => fragment_id(fragment), :disabled => input_html_options[:disabled] )
end.join.html_safe
end
def fragment_value(fragment)
if fragment == :year
Time.now.year
else
'1'
end
end
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/inputs/datalist_input.rb
|
module Formtastic
module Inputs
# Outputs a label and a text field, along with a datalist tag
# datalist tag provides a list of options which drives a simple autocomplete
# on the text field. This is a HTML5 feature, more info can be found at
# {https://developer.mozilla.org/en/docs/Web/HTML/Element/datalist <datalist> at MDN}
# This input accepts a :collection option which takes data in all the usual formats accepted by
# {http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select options_for_select}
#
# @example Input is used as follows
# f.input :fav_book, :as => :datalist, :collection => Book.pluck(:name)
#
class DatalistInput
include Base
include Base::Stringish
include Base::Collections
def to_html
@name = input_html_options[:id].gsub(/_id$/, "")
input_wrapping do
label_html <<
builder.text_field(method, input_html_options) << # standard input
data_list_html # append new datalist element
end
end
def input_html_options
super.merge(:list => html_id_of_datalist)
end
def html_id_of_datalist
"#{@name}_datalist"
end
def data_list_html
html = builder.template.options_for_select(collection)
builder.template.content_tag(:datalist,html, { :id => html_id_of_datalist }, false)
end
end
end
end
|
ryanfox1985/formtastic
|
spec/action_class_finder_spec.rb
|
<reponame>ryanfox1985/formtastic<filename>spec/action_class_finder_spec.rb
# encoding: utf-8
require 'spec_helper'
require 'formtastic/action_class_finder'
RSpec.describe Formtastic::ActionClassFinder do
include FormtasticSpecHelper
it_behaves_like 'Specialized Class Finder' do
let(:default) { Formtastic::Actions }
let(:namespaces_setting) { :action_namespaces }
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/input_class_finder.rb
|
<reponame>ryanfox1985/formtastic
module Formtastic
# Uses the {Formtastic::NamespacedClassFinder} to look up input class names.
#
# See {Formtastic::FormBuilder#namespaced_input_class} for details.
#
class InputClassFinder < NamespacedClassFinder
# @param builder [FormBuilder]
def initialize(builder)
super builder.input_namespaces
end
def class_name(as)
"#{super}Input"
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/util.rb
|
<gh_stars>1-10
# encoding: utf-8
module Formtastic
# @private
module Util
extend self
def deprecated_version_of_rails?
match?(rails_version, "< #{minimum_version_of_rails}")
end
def minimum_version_of_rails
"4.1.0"
end
def rails_version
::Rails::VERSION::STRING
end
def match?(version, dependency)
Gem::Dependency.new("formtastic", dependency).match?("formtastic", version)
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/inputs/base/naming.rb
|
module Formtastic
module Inputs
module Base
module Naming
def as
self.class.name.split("::")[-1].underscore.gsub(/_input$/, '')
end
def sanitized_object_name
object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
end
def sanitized_method_name
@sanitized_method_name ||= method.to_s.gsub(/[\?\/\-]$/, '')
end
def attributized_method_name
method.to_s.gsub(/_id$/, '').to_sym
end
def humanized_method_name
if builder.label_str_method != :humanize
# Special case where label_str_method should trump the human_attribute_name
# TODO: is this actually a desired bheavior, or should we ditch label_str_method and
# rely purely on :human_attribute_name.
method.to_s.send(builder.label_str_method)
elsif object && object.class.respond_to?(:human_attribute_name)
object.class.human_attribute_name(method.to_s)
else
method.to_s.send(builder.label_str_method)
end
end
def input_name
association_primary_key
end
end
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/inputs/base/timeish.rb
|
<filename>lib/formtastic/inputs/base/timeish.rb
module Formtastic
module Inputs
module Base
# Timeish inputs (`:date_select`, `:datetime_select`, `:time_select`) are similar to the Rails date and time
# helpers (`date_select`, `datetime_select`, `time_select`), rendering a series of `<select>`
# tags for each fragment (year, month, day, hour, minute, seconds). The fragments are then
# re-combined to a date by ActiveRecord through multi-parameter assignment.
#
# The mark-up produced by Rails is simple but far from ideal, with no way to label the
# individual fragments for accessibility, no fieldset to group the related fields, and no
# legend describing the group. Formtastic addresses this within the standard `<li>` wrapper
# with a `<fieldset>` with a `<legend>` as a label, followed by an ordered list (`<ol>`) of
# list items (`<li>`), one for each fragment (year, month, ...). Each `<li>` fragment contains
# a `<label>` (eg "Year") for the fragment, and a `<select>` containing `<option>`s (eg a
# range of years).
#
# In the supplied formtastic.css file, the resulting mark-up is styled to appear a lot like a
# standard Rails date time select by:
#
# * styling the legend to look like the other labels (to the left hand side of the selects)
# * floating the `<li>` fragments against each other as a single line
# * hiding the `<label>` of each fragment with `display:none`
#
# @example `:date_select` input with full form context and sample HTMl output
#
# <%= semantic_form_for(@post) do |f| %>
# <%= f.inputs do %>
# ...
# <%= f.input :publish_at, :as => :date_select %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset class="inputs">
# <ol>
# <li class="date">
# <fieldset class="fragments">
# <ol class="fragments-group">
# <li class="fragment">
# <label for="post_publish_at_1i">Year</label>
# <select id="post_publish_at_1i" name="post[publish_at_1i]">...</select>
# </li>
# <li class="fragment">
# <label for="post_publish_at_2i">Month</label>
# <select id="post_publish_at_2i" name="post[publish_at_2i]">...</select>
# </li>
# <li class="fragment">
# <label for="post_publish_at_3i">Day</label>
# <select id="post_publish_at_3i" name="post[publish_at_3i]">...</select>
# </li>
# </ol>
# </fieldset>
# </li>
# </ol>
# </fieldset>
# </form>
#
#
# @example `:time_select` input
# <%= f.input :publish_at, :as => :time_select %>
#
# @example `:datetime_select` input
# <%= f.input :publish_at, :as => :datetime_select %>
#
# @example Change the labels for each fragment
# <%= f.input :publish_at, :as => :date_select, :labels => { :year => "Y", :month => "M", :day => "D" } %>
#
# @example Suppress the labels for all fragments
# <%= f.input :publish_at, :as => :date_select, :labels => false %>
#
# @example Skip a fragment (defaults to 1, skips all following fragments)
# <%= f.input :publish_at, :as => :datetime_select, :discard_minute => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_hour => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_day => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_month => true %>
# <%= f.input :publish_at, :as => :datetime_select, :discard_year => true %>
#
# @example Change the order
# <%= f.input :publish_at, :as => :date_select, :order => [:month, :day, :year] %>
#
# @example Include seconds with times (excluded by default)
# <%= f.input :publish_at, :as => :time_select, :include_seconds => true %>
#
# @example Specify if there should be a blank option at the start of each select or not. Note that, unlike select inputs, :include_blank does not accept a string value.
# <%= f.input :publish_at, :as => :time_select, :include_blank => true %>
# <%= f.input :publish_at, :as => :time_select, :include_blank => false %>
#
# @todo Document i18n
# @todo Check what other Rails options are supported (`start_year`, `end_year`, `use_month_numbers`, `use_short_month`, `add_month_numbers`, `prompt`), write tests for them, and otherwise support them
# @todo Could we take the rendering from Rails' helpers and inject better HTML in and around it rather than re-inventing the whee?
module Timeish
def to_html
input_wrapping do
fragments_wrapping do
hidden_fragments <<
fragments_label <<
template.content_tag(:ol,
fragments.map do |fragment|
fragment_wrapping do
fragment_label_html(fragment) <<
fragment_input_html(fragment)
end
end.join.html_safe, # TODO is this safe?
{ :class => 'fragments-group' } # TODO refactor to fragments_group_wrapping
)
end
end
end
def fragments
date_fragments + time_fragments
end
def time_fragments
options[:include_seconds] ? [:hour, :minute, :second] : [:hour, :minute]
end
def date_fragments
options[:order] || i18n_date_fragments || default_date_fragments
end
def default_date_fragments
[:year, :month, :day]
end
def fragment_wrapping(&block)
template.content_tag(:li, template.capture(&block), fragment_wrapping_html_options)
end
def fragment_wrapping_html_options
{ :class => 'fragment' }
end
def fragment_label(fragment)
labels_from_options = options.key?(:labels) ? options[:labels] : {}
if !labels_from_options
''
elsif labels_from_options.key?(fragment)
labels_from_options[fragment]
else
::I18n.t(fragment.to_s, :default => fragment.to_s.humanize, :scope => [:datetime, :prompts])
end
end
def fragment_id(fragment)
"#{input_html_options[:id]}_#{position(fragment)}i"
end
def fragment_name(fragment)
"#{method}(#{position(fragment)}i)"
end
def fragment_label_html(fragment)
text = fragment_label(fragment)
text.blank? ? "".html_safe : template.content_tag(:label, text, :for => fragment_id(fragment))
end
def value
object.send(method) if object && object.respond_to?(method)
end
def fragment_input_html(fragment)
opts = input_options.merge(:prefix => fragment_prefix, :field_name => fragment_name(fragment), :default => value, :include_blank => include_blank?)
template.send(:"select_#{fragment}", value, opts, input_html_options.merge(:id => fragment_id(fragment)))
end
def fragment_prefix
if builder.options.key?(:index)
object_name + "[#{builder.options[:index]}]"
else
object_name
end
end
# TODO extract to BlankOptions or similar -- Select uses similar code
def include_blank?
options.key?(:include_blank) ? options[:include_blank] : builder.include_blank_for_select_by_default
end
def positions
{ :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
end
def position(fragment)
positions[fragment]
end
def i18n_date_fragments
order = ::I18n.t(:order, :scope => [:date])
if order.is_a?(Array)
order.map &:to_sym
else
nil
end
end
def fragments_wrapping(&block)
template.content_tag(:fieldset,
template.capture(&block).html_safe,
fragments_wrapping_html_options
)
end
def fragments_wrapping_html_options
{ :class => "fragments" }
end
def fragments_label
if render_label?
template.content_tag(:legend,
builder.label(method, label_text, :for => fragment_id(fragments.first)),
:class => "label"
)
else
"".html_safe
end
end
def fragments_inner_wrapping(&block)
template.content_tag(:ol,
template.capture(&block)
)
end
def hidden_fragments
"".html_safe
end
def hidden_field_name(fragment)
if builder.options.key?(:index)
"#{object_name}[#{builder.options[:index]}][#{fragment_name(fragment)}]"
else
"#{object_name}[#{fragment_name(fragment)}]"
end
end
end
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/version.rb
|
module Formtastic
VERSION = "3.2.0.pre"
end
|
ryanfox1985/formtastic
|
lib/formtastic/inputs/base/database.rb
|
<gh_stars>1-10
module Formtastic
module Inputs
module Base
module Database
def column
if object.respond_to?(:column_for_attribute)
# Remove deprecation wrapper & review after Rails 5.0 ships
ActiveSupport::Deprecation.silence do
object.column_for_attribute(method)
end
end
end
def column?
!column.nil?
end
end
end
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/inputs/base/fileish.rb
|
<reponame>ryanfox1985/formtastic
module Formtastic
module Inputs
module Base
module Fileish
def file?
@file ||= begin
# TODO return true if self.is_a?(Formtastic::Inputs::FileInput::Woo)
object && object.respond_to?(method) && builder.file_methods.any? { |m| object.send(method).respond_to?(m) }
end
end
end
end
end
end
|
ryanfox1985/formtastic
|
spec/generators/formtastic/input/input_generator_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
require 'generators/formtastic/input/input_generator'
RSpec.describe Formtastic::InputGenerator do
include FormtasticSpecHelper
destination File.expand_path("../../../../../tmp", __FILE__)
before do
prepare_destination
end
after do
FileUtils.rm_rf(File.expand_path("../../../../../tmp", __FILE__))
end
describe 'without file name' do
it 'should raise Thor::RequiredArgumentMissingError' do
expect { run_generator }.to raise_error(Thor::RequiredArgumentMissingError)
end
end
describe "input generator with underscore definition" do
before { run_generator %w(hat_size)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
it { is_expected.to contain "def to_html"}
it { is_expected.to contain "include Formtastic::Inputs::Base"}
it { is_expected.not_to contain "super"}
end
end
describe "input generator with camelcase definition" do
before { run_generator %w(HatSize)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "input generator with camelcase Input name sufixed" do
before { run_generator %w(HatSizeInput)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "input generator with underscore _input name sufixed" do
before { run_generator %w(hat_size_input)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "input generator with underscore input name sufixed" do
before { run_generator %w(hat_sizeinput)}
describe 'generate an input in its respective folder' do
subject{ file('app/inputs/hat_size_input.rb')}
it { is_expected.to exist}
it { is_expected.to contain "class HatSizeInput"}
end
end
describe "override an existing input using extend" do
before { run_generator %w(string --extend)}
describe 'app/inputs/string_input.rb' do
subject{ file('app/inputs/string_input.rb')}
it { is_expected.to exist }
it { is_expected.to contain "class StringInput < Formtastic::Inputs::StringInput" }
it { is_expected.to contain "def to_html" }
it { is_expected.not_to contain "include Formtastic::Inputs::Base" }
it { is_expected.to contain "super" }
it { is_expected.not_to contain "def input_html_options" }
end
end
describe "extend an existing input" do
before { run_generator %w(FlexibleText --extend string)}
describe 'app/inputs/flexible_text_input.rb' do
subject{ file('app/inputs/flexible_text_input.rb')}
it { is_expected.to contain "class FlexibleTextInput < Formtastic::Inputs::StringInput" }
it { is_expected.to contain "def input_html_options" }
it { is_expected.not_to contain "include Formtastic::Inputs::Base" }
it { is_expected.not_to contain "def to_html" }
end
end
describe "provide a slashed namespace" do
before { run_generator %w(stuff/foo)}
describe 'app/inputs/stuff/foo_input.rb' do
subject{ file('app/inputs/stuff/foo_input.rb')}
it {is_expected.to exist}
it { is_expected.to contain "class Stuff::FooInput" }
it { is_expected.to contain "include Formtastic::Inputs::Base" }
end
end
describe "provide a camelized namespace" do
before { run_generator %w(Stuff::Foo)}
describe 'app/inputs/stuff/foo_input.rb' do
subject{ file('app/inputs/stuff/foo_input.rb')}
it {is_expected.to exist}
it { is_expected.to contain "class Stuff::FooInput" }
it { is_expected.to contain "include Formtastic::Inputs::Base" }
end
end
end
|
ryanfox1985/formtastic
|
spec/inputs/base/validations_spec.rb
|
<gh_stars>0
require 'fast_spec_helper'
require 'inputs/base/validations'
class MyInput
include Formtastic::Inputs::Base::Validations
end
RSpec.describe MyInput do
let(:builder) { double }
let(:template) { double }
let(:model_class) { double }
let(:model) { double(:class => model_class) }
let(:model_name) { "post" }
let(:method) { double }
let(:options) { Hash.new }
let(:validator) { double }
let(:instance) { MyInput.new(builder, template, model, model_name, method, options) }
describe '#required?' do
context 'with a single validator' do
before :example do
allow(instance).to receive(:validations?).and_return(:true)
allow(instance).to receive(:validations).and_return([validator])
end
context 'with options[:required] being true' do
let(:options) { {required: true} }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with options[:required] being false' do
let(:options) { {required: false} }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'with negated validation' do
it 'is not required' do
instance.not_required_through_negated_validation!
expect(instance.required?).to be_falsey
end
end
context 'with presence validator' do
let (:validator) { double(options: {}, kind: :presence) }
it 'is required' do
expect(instance.required?).to be_truthy
end
context 'with options[:on] as symbol' do
context 'with save context' do
let (:validator) { double(options: {on: :save}, kind: :presence) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with create context' do
let (:validator) { double(options: {on: :create}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is not required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_falsey
end
end
context 'with update context' do
let (:validator) { double(options: {on: :update}, kind: :presence) }
it 'is not required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_falsey
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
end
context 'with options[:on] as array' do
context 'with save context' do
let (:validator) { double(options: {on: [:save]}, kind: :presence) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with create context' do
let (:validator) { double(options: {on: [:create]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is not required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_falsey
end
end
context 'with update context' do
let (:validator) { double(options: {on: [:update]}, kind: :presence) }
it 'is not required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_falsey
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with save and create context' do
let (:validator) { double(options: {on: [:save, :create]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with save and update context' do
let (:validator) { double(options: {on: [:save, :create]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with create and update context' do
let (:validator) { double(options: {on: [:create, :update]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with save and other context' do
let (:validator) { double(options: {on: [:save, :foo]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
context 'with create and other context' do
let (:validator) { double(options: {on: [:create, :foo]}, kind: :presence) }
it 'is required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_truthy
end
it 'is not required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_falsey
end
end
context 'with update and other context' do
let (:validator) { double(options: {on: [:update, :foo]}, kind: :presence) }
it 'is not required for new records' do
allow(model).to receive(:new_record?).and_return(true)
expect(instance.required?).to be_falsey
end
it 'is required for existing records' do
allow(model).to receive(:new_record?).and_return(false)
expect(instance.required?).to be_truthy
end
end
end
end
context 'with inclusion validator' do
context 'with allow blank' do
let (:validator) { double(options: {allow_blank: true}, kind: :inclusion) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'without allow blank' do
let (:validator) { double(options: {allow_blank: false}, kind: :inclusion) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
end
context 'with a length validator' do
context 'with allow blank' do
let (:validator) { double(options: {allow_blank: true}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'without allow blank' do
let (:validator) { double(options: {allow_blank: false}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
context 'with a minimum > 0' do
let (:validator) { double(options: {allow_blank: false, minimum: 1}, kind: :length) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a minimum <= 0' do
let (:validator) { double(options: {allow_blank: false, minimum: 0}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
context 'with a defined range starting with > 0' do
let (:validator) { double(options: {allow_blank: false, within: 1..5}, kind: :length) }
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a defined range starting with <= 0' do
let (:validator) { double(options: {allow_blank: false, within: 0..5}, kind: :length) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
end
end
context 'with another validator' do
let (:validator) { double(options: {allow_blank: true}, kind: :foo) }
it 'is not required' do
expect(instance.required?).to be_falsey
end
end
end
context 'with multiple validators' do
context 'with a on create presence validator and a on update presence validator' do
let (:validator1) { double(options: {on: :create}, kind: :presence) }
let (:validator2) { double(options: {}, kind: :presence) }
before :example do
allow(model).to receive(:new_record?).and_return(false)
allow(instance).to receive(:validations?).and_return(:true)
allow(instance).to receive(:validations).and_return([validator1, validator2])
end
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a on create presence validator and a presence validator' do
let (:validator1) { double(options: {on: :create}, kind: :presence) }
let (:validator2) { double(options: {}, kind: :presence) }
before :example do
allow(model).to receive(:new_record?).and_return(false)
allow(instance).to receive(:validations?).and_return(:true)
allow(instance).to receive(:validations).and_return([validator1, validator2])
end
it 'is required' do
expect(instance.required?).to be_truthy
end
end
context 'with a on create presence validator and a allow blank inclusion validator' do
let (:validator1) { double(options: {on: :create}, kind: :presence) }
let (:validator2) { double(options: {allow_blank: true}, kind: :inclusion) }
before :example do
allow(model).to receive(:new_record?).and_return(false)
allow(instance).to receive(:validations?).and_return(:true)
allow(instance).to receive(:validations).and_return([validator1, validator2])
end
it 'is required' do
expect(instance.required?).to be_falsey
end
end
end
end
end
|
ryanfox1985/formtastic
|
spec/inputs/hidden_input_spec.rb
|
<gh_stars>1-10
# encoding: utf-8
require 'spec_helper'
RSpec.describe 'hidden input' do
include FormtasticSpecHelper
before do
@output_buffer = ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden))
concat(builder.input(:published, :as => :hidden, :input_html => {:value => true}))
concat(builder.input(:reviewer, :as => :hidden, :input_html => {:class => 'new_post_reviewer', :id => 'new_post_reviewer'}))
end)
end
it_should_have_input_wrapper_with_class("hidden")
it_should_have_input_wrapper_with_class(:input)
it_should_have_input_wrapper_with_id("post_secret_input")
it_should_not_have_a_label
it "should generate a input field" do
expect(output_buffer).to have_tag("form li input#post_secret")
expect(output_buffer).to have_tag("form li input#post_secret[@type=\"hidden\"]")
expect(output_buffer).to have_tag("form li input#post_secret[@name=\"post[secret]\"]")
end
it "should get value from the object" do
expect(output_buffer).to have_tag("form li input#post_secret[@type=\"hidden\"][@value=\"1\"]")
end
it "should pass any explicitly specified value - using :input_html options" do
expect(output_buffer).to have_tag("form li input#post_published[@type=\"hidden\"][@value=\"true\"]")
end
it "should pass any option specified using :input_html" do
expect(output_buffer).to have_tag("form li input#new_post_reviewer[@type=\"hidden\"][@class=\"new_post_reviewer\"]")
end
it "should not render inline errors" do
@errors = double('errors')
allow(@errors).to receive(:[]).with(errors_matcher(:secret)).and_return(["foo", "bah"])
allow(@new_post).to receive(:errors).and_return(@errors)
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden))
end)
expect(output_buffer).not_to have_tag("form li p.inline-errors")
expect(output_buffer).not_to have_tag("form li ul.errors")
end
it "should not render inline hints" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:secret, :as => :hidden, :hint => "all your base are belong to use"))
end)
expect(output_buffer).not_to have_tag("form li p.inline-hints")
expect(output_buffer).not_to have_tag("form li ul.hints")
end
describe "when namespace is provided" do
before do
@output_buffer = ''
mock_everything
concat(semantic_form_for(@new_post, :namespace => 'context2') do |builder|
concat(builder.input(:secret, :as => :hidden))
concat(builder.input(:published, :as => :hidden, :input_html => {:value => true}))
concat(builder.input(:reviewer, :as => :hidden, :input_html => {:class => 'new_post_reviewer', :id => 'new_post_reviewer'}))
end)
end
attributes_to_check = [:secret, :published, :reviewer]
attributes_to_check.each do |a|
it_should_have_input_wrapper_with_id("context2_post_#{a}_input")
end
(attributes_to_check - [:reviewer]).each do |a|
it_should_have_input_with_id("context2_post_#{a}")
end
end
describe "when index is provided" do
before do
@output_buffer = ''
mock_everything
concat(semantic_form_for(@new_post) do |builder|
concat(builder.fields_for(:author, :index => 3) do |author|
concat(author.input(:name, :as => :hidden))
end)
end)
end
it 'should index the id of the wrapper' do
expect(output_buffer).to have_tag("li#post_author_attributes_3_name_input")
end
it 'should index the id of the select tag' do
expect(output_buffer).to have_tag("input#post_author_attributes_3_name")
end
it 'should index the name of the select tag' do
expect(output_buffer).to have_tag("input[@name='post[author_attributes][3][name]']")
end
end
context "when required" do
it "should not add the required attribute to the input's html options" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :hidden, :required => true))
end)
expect(output_buffer).not_to have_tag("input[@required]")
end
end
context "when :autofocus is provided in :input_html" do
it "should not add the autofocus attribute to the input's html options" do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.input(:title, :as => :hidden, :input_html => {:autofocus => true}))
end)
expect(output_buffer).not_to have_tag("input[@autofocus]")
end
end
end
|
ryanfox1985/formtastic
|
spec/fast_spec_helper.rb
|
# encoding: utf-8
$LOAD_PATH << 'lib/formtastic'
require 'active_support/all'
require 'localized_string'
require 'inputs'
require 'helpers'
class MyInput
include Formtastic::Inputs::Base
end
I18n.enforce_available_locales = false if I18n.respond_to?(:enforce_available_locales)
|
ryanfox1985/formtastic
|
lib/formtastic/helpers/input_helper.rb
|
# -*- coding: utf-8 -*-
module Formtastic
module Helpers
# {#input} is used to render all content (labels, form widgets, error messages, hints, etc) for
# a single form input (or field), usually representing a single method or attribute on the
# form's object or model.
#
# The content is wrapped in an `<li>` tag, so it's usually called inside an {Formtastic::Helpers::InputsHelper#inputs inputs} block
# (which renders an `<ol>` inside a `<fieldset>`), which should be inside a {Formtastic::Helpers::FormHelper#semantic_form_for `semantic_form_for`}
# block:
#
# <%= semantic_form_for @post do |f| %>
# <%= f.inputs do %>
# <%= f.input :title %>
# <%= f.input :body %>
# <% end %>
# <% end %>
#
# The HTML output will be something like:
#
# <form class="formtastic" method="post" action="...">
# <fieldset>
# <ol>
# <li class="string required" id="post_title_input">
# ...
# </li>
# <li class="text required" id="post_body_input">
# ...
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see #input
# @see Formtastic::Helpers::InputsHelper#inputs
# @see Formtastic::Helpers::FormHelper#semantic_form_for
module InputHelper
include Formtastic::Helpers::Reflection
include Formtastic::Helpers::Enum
include Formtastic::Helpers::FileColumnDetection
# Returns a chunk of HTML markup for a given `method` on the form object, wrapped in
# an `<li>` wrapper tag with appropriate `class` and `id` attribute hooks for CSS and JS.
# In many cases, the contents of the wrapper will be as simple as a `<label>` and an `<input>`:
#
# <%= f.input :title, :as => :string, :required => true %>
#
# <li class="string required" id="post_title_input">
# <label for="post_title">Title<abbr title="Required">*</abbr></label>
# <input type="text" name="post[title]" value="" id="post_title" required="required">
# </li>
#
# In other cases (like a series of checkboxes for a `has_many` relationship), the wrapper may
# include more complex markup, like a nested `<fieldset>` with a `<legend>` and an `<ol>` of
# checkbox/label pairs for each choice:
#
# <%= f.input :categories, :as => :check_boxes, :collection => Category.active.ordered %>
#
# <li class="check_boxes" id="post_categories_input">
# <fieldset>
# <legend>Categories</legend>
# <ol>
# <li>
# <label><input type="checkbox" name="post[categories][1]" value="1"> Ruby</label>
# </li>
# <li>
# <label><input type="checkbox" name="post[categories][2]" value="2"> Rails</label>
# </li>
# <li>
# <label><input type="checkbox" name="post[categories][2]" value="2"> Awesome</label>
# </li>
# </ol>
# </fieldset>
# </li>
#
# Sensible defaults for all options are guessed by looking at the method name, database column
# information, association information, validation information, etc. For example, a `:string`
# database column will map to a `:string` input, but if the method name contains 'email', will
# map to an `:email` input instead. `belongs_to` associations will have a `:select` input, etc.
#
# Formtastic supports many different styles of inputs, and you can/should override the default
# with the `:as` option. Internally, the symbol is used to map to a protected method
# responsible for the details. For example, `:as => :string` will map to `string_input`,
# defined in a module of the same name. Detailed documentation for each input style and it's
# supported options is available on the `*_input` method in each module (links provided below).
#
# Available input styles:
#
# * `:boolean` (see {Inputs::BooleanInput})
# * `:check_boxes` (see {Inputs::CheckBoxesInput})
# * `:color` (see {Inputs::ColorInput})
# * `:country` (see {Inputs::CountryInput})
# * `:datetime_select` (see {Inputs::DatetimeSelectInput})
# * `:date_select` (see {Inputs::DateSelectInput})
# * `:email` (see {Inputs::EmailInput})
# * `:file` (see {Inputs::FileInput})
# * `:hidden` (see {Inputs::HiddenInput})
# * `:number` (see {Inputs::NumberInput})
# * `:password` (see {Inputs::PasswordInput})
# * `:phone` (see {Inputs::PhoneInput})
# * `:radio` (see {Inputs::RadioInput})
# * `:search` (see {Inputs::SearchInput})
# * `:select` (see {Inputs::SelectInput})
# * `:string` (see {Inputs::StringInput})
# * `:text` (see {Inputs::TextInput})
# * `:time_zone` (see {Inputs::TimeZoneInput})
# * `:time_select` (see {Inputs::TimeSelectInput})
# * `:url` (see {Inputs::UrlInput})
#
# Calling `:as => :string` (for example) will call `#to_html` on a new instance of
# `Formtastic::Inputs::StringInput`. Before this, Formtastic will try to instantiate a top-level
# namespace StringInput, meaning you can subclass and modify `Formtastic::Inputs::StringInput`
# in `app/inputs/`. This also means you can create your own new input types in `app/inputs/`.
#
# @todo document the "guessing" of input style
#
# @param [Symbol] method
# The database column or method name on the form object that this input represents
#
# @option options :as [Symbol]
# Override the style of input should be rendered
#
# @option options :label [String, Symbol, false]
# Override the label text
#
# @option options :hint [String, Symbol, false]
# Override hint text
#
# @option options :required [Boolean]
# Override to mark the input as required (or not) — adds a required/optional class to the wrapper, and a HTML5 required attribute to the `<input>`
#
# @option options :input_html [Hash]
# Override or add to the HTML attributes to be passed down to the `<input>` tag
# (If you use attr_readonly method in your model, formtastic will automatically set those attributes's input readonly)
#
# @option options :wrapper_html [Hash]
# Override or add to the HTML attributes to be passed down to the wrapping `<li>` tag
#
# @option options :collection [Array<ActiveModel, String, Symbol>, Hash{String => String, Boolean}, OrderedHash{String => String, Boolean}]
# Override collection of objects in the association (`:select`, `:radio` & `:check_boxes` inputs only)
#
# @option options :multiple [Boolean]
# Specify if the `:select` input should allow multiple selections or not (defaults to `belongs_to` associations, and `true` for `has_many` and `has_and_belongs_to_many` associations)
#
# @option options :include_blank [Boolean]
# Specify if a `:select` input should include a blank option or not (defaults to `include_blank_for_select_by_default` configuration)
#
# @option options :prompt [String]
# Specify the text in the first ('blank') `:select` input `<option>` to prompt a user to make a selection (implicitly sets `:include_blank` to `true`)
#
# @todo Can we deprecate & kill `:label`, `:hint` & `:prompt`? All strings could be shifted to i18n!
#
# @example Accept all default options
# <%= f.input :title %>
#
# @example Change the input type
# <%= f.input :title, :as => :string %>
#
# @example Changing the label with a String
# <%= f.input :title, :label => "Post title" %>
#
# @example Disabling the label with false, even if an i18n translation exists
# <%= f.input :title, :label => false %>
#
# @example Changing the hint with a String
# <%= f.input :title, :hint => "Every post needs a title!" %>
#
# @example Disabling the hint with false, even if an i18n translation exists
# <%= f.input :title, :hint => false %>
#
# @example Marking a field as required or not (even if validations do not enforce it)
# <%= f.input :title, :required => true %>
# <%= f.input :title, :required => false %>
#
# @example Changing or adding to HTML attributes in the main `<input>` or `<select>` tag
# <%= f.input :title, :input_html => { :onchange => "somethingAwesome();", :class => 'awesome' } %>
#
# @example Changing or adding to HTML attributes in the wrapper `<li>` tag
# <%= f.input :title, :wrapper_html => { :class => "important-input" } %>
#
# @example Changing the association choices with `:collection`
# <%= f.input :author, :collection => User.active %>
# <%= f.input :categories, :collection => Category.where(...).order(...) %>
# <%= f.input :status, :collection => ["Draft", "Published"] %>
# <%= f.input :status, :collection => [:draft, :published] %>
# <%= f.input :status, :collection => {"Draft" => 0, "Published" => 1} %>
# <%= f.input :status, :collection => OrderedHash.new("Draft" => 0, "Published" => 1) %>
# <%= f.input :status, :collection => [["Draft", 0], ["Published", 1]] %>
# <%= f.input :status, :collection => grouped_options_for_select(...) %>
# <%= f.input :status, :collection => options_for_select(...) %>
#
# @example Specifying if a `:select` should allow multiple selections:
# <%= f.input :cateogies, :as => :select, :multiple => true %>
# <%= f.input :cateogies, :as => :select, :multiple => false %>
#
# @example Specifying if a `:select` should have a 'blank' first option to prompt selection:
# <%= f.input :author, :as => :select, :include_blank => true %>
# <%= f.input :author, :as => :select, :include_blank => false %>
#
# @example Specifying the text for a `:select` input's 'blank' first option to prompt selection:
# <%= f.input :author, :as => :select, :prompt => "Select an Author" %>
#
# @example Modifying an input to suit your needs in `app/inputs`:
# class StringInput < Formtastic::Inputs::StringInput
# def to_html
# puts "this is my custom version of StringInput"
# super
# end
# end
#
# @example Creating your own input to suit your needs in `app/inputs`:
# class DatePickerInput
# include Formtastic::Inputs::Base
# def to_html
# # ...
# end
# end
#
# @example Providing HTML5 placeholder text through i18n:
# en:
# formtastic:
# placeholders:
# user:
# email: "<EMAIL>"
# first_name: "Joe"
# last_name: "Smith"
#
# @see #namespaced_input_class
# @todo Many many more examples. Some of the detail probably needs to be pushed out to the relevant methods too.
# @todo More i18n examples.
def input(method, options = {})
method = method.to_sym
options = options.dup # Allow options to be shared without being tainted by Formtastic
options[:as] ||= default_input_type(method, options)
klass = namespaced_input_class(options[:as])
klass.new(self, template, @object, @object_name, method, options).to_html
end
protected
# First try if we can detect special things like :file. With CarrierWave the method does have
# an underlying column so we don't want :string to get selected.
#
# For methods that have a database column, take a best guess as to what the input method
# should be. In most cases, it will just return the column type (eg :string), but for special
# cases it will simplify (like the case of :integer, :float & :decimal to :number), or do
# something different (like :password and :select).
#
# If there is no column for the method (eg "virtual columns" with an attr_accessor), the
# default is a :string, a similar behaviour to Rails' scaffolding.
def default_input_type(method, options = {}) # @private
if @object
return :select if reflection_for(method)
return :file if is_file?(method, options)
end
column = column_for(method)
if column && column.type
# Special cases where the column type doesn't map to an input method.
case column.type
when :string
return :password if method.to_s =~ /password/
return :country if method.to_s =~ /country$/
return :time_zone if method.to_s =~ /time_zone/
return :email if method.to_s =~ /email/
return :url if method.to_s =~ /^url$|^website$|_url$/
return :phone if method.to_s =~ /(phone|fax)/
return :search if method.to_s =~ /^search$/
return :color if method.to_s =~ /color/
when :integer
return :select if reflection_for(method)
return :select if enum_for(method)
return :number
when :float, :decimal
return :number
when :datetime, :timestamp
return :datetime_select
when :time
return :time_select
when :date
return :date_select
when :hstore
return :text
end
# Try look for hints in options hash. Quite common senario: Enum keys stored as string in the database.
return :select if column.type == :string && options.key?(:collection)
# Try 3: Assume the input name will be the same as the column type (e.g. string_input).
return column.type
else
return :select if options.key?(:collection)
return :password if method.to_s =~ /password/
return :string
end
end
# Get a column object for a specified attribute method - if possible.
def column_for(method) # @private
if @object.respond_to?(:column_for_attribute)
# Remove deprecation wrapper & review after Rails 5.0 ships
ActiveSupport::Deprecation.silence do
@object.column_for_attribute(method)
end
end
end
# Takes the `:as` option and attempts to return the corresponding input
# class. In the case of `:as => :awesome` it will first attempt to find a
# top level `AwesomeInput` class (to allow the application to subclass
# and modify to suit), falling back to `Formtastic::Inputs::AwesomeInput`.
#
# Custom input namespaces to look into can be configured via the
# {Formtastic::FormBuilder.input_namespaces} configuration setting.
#
# @param [Symbol] as A symbol representing the type of input to render
# @raise [Formtastic::UnknownInputError] An appropriate input class could not be found
# @return [Class] An input class constant
#
# @example Normal use
# input_class(:string) #=> Formtastic::Inputs::StringInput
# input_class(:date) #=> Formtastic::Inputs::DateInput
#
# @example When a top-level class is found
# input_class(:string) #=> StringInput
# input_class(:awesome) #=> AwesomeInput
# @see NamespacedClassFinder#find
def namespaced_input_class(as)
@input_class_finder ||= input_class_finder.new(self)
@input_class_finder.find(as)
rescue Formtastic::InputClassFinder::NotFoundError
raise Formtastic::UnknownInputError, "Unable to find input #{$!.message}"
end
end
end
end
|
ryanfox1985/formtastic
|
spec/input_class_finder_spec.rb
|
# encoding: utf-8
require 'spec_helper'
require 'formtastic/input_class_finder'
RSpec.describe Formtastic::InputClassFinder do
it_behaves_like 'Specialized Class Finder' do
let(:default) { Formtastic::Inputs }
let(:namespaces_setting) { :input_namespaces }
end
end
|
ryanfox1985/formtastic
|
lib/formtastic/action_class_finder.rb
|
module Formtastic
# Uses the {NamespacedClassFinder} to look up action class names.
#
# See {Formtastic::Helpers::ActionHelper#namespaced_action_class} for details.
#
class ActionClassFinder < NamespacedClassFinder
# @param builder [FormBuilder]
def initialize(builder)
super builder.action_namespaces
end
def class_name(as)
"#{super}Action"
end
end
end
|
ryanfox1985/formtastic
|
lib/generators/formtastic/form/form_generator.rb
|
<reponame>ryanfox1985/formtastic
# encoding: utf-8
module Formtastic
# Generates a Formtastic form partial based on an existing model. It will not overwrite existing
# files without confirmation.
#
# @example
# !!!shell
# $ rails generate formtastic:form Post
# @example Copy the partial code to the pasteboard rather than generating a partial
# !!!shell
# $ rails generate formtastic:form Post --copy
# @example Return HAML or Slim output instead of default ERB
# !!!shell
# $ rails generate formtastic:form Post --template-engine haml
# $ rails generate formtastic:form Post --template-engine slim
# @example Generate a form for specific model attributes
# !!!shell
# $ rails generate formtastic:form Post title:string body:text
# @example Generate a form for a specific controller
# !!!shell
# $ rails generate formtastic:form Post --controller admin/posts
class FormGenerator < Rails::Generators::NamedBase
desc "Generates a Formtastic form partial based on an existing model."
argument :name, :type => :string, :required => true, :banner => 'MODEL_NAME'
argument :attributes, :type => :array, :default => [], :banner => 'attribute attribute'
source_root File.expand_path('../../../templates', __FILE__)
class_option :template_engine
class_option :copy, :type => :boolean, :default => false, :group => :formtastic,
:desc => 'Copy the generated code the clipboard instead of generating a partial file."'
class_option :controller, :type => :string, :default => false, :group => :formtastic,
:desc => 'Generate for custom controller/view path - in case model and controller namespace is different, i.e. "admin/posts"'
def create_or_show
@attributes = reflected_attributes if @attributes.empty?
engine = options[:template_engine]
if options[:copy]
template = File.read("#{self.class.source_root}/_form.html.#{engine}")
erb = ERB.new(template, nil, '-')
generated_code = erb.result(binding).strip rescue nil
puts "The following code has been copied to the clipboard, just paste it in your views:" if save_to_clipboard(generated_code)
puts generated_code || "Error: Nothing generated. Does the model exist?"
else
empty_directory "app/views/#{controller_path}"
template "_form.html.#{engine}", "app/views/#{controller_path}/_form.html.#{engine}"
end
end
protected
def controller_path
@controller_path ||= if options[:controller]
options[:controller].underscore
else
name.underscore.pluralize
end
end
def reflected_attributes
columns = content_columns
columns += association_columns
end
def model
@model ||= name.camelize.constantize
end
# Collects content columns (non-relation columns) for the current class.
# Skips Active Record Timestamps.
def content_columns
model.content_columns.select do |column|
!Formtastic::FormBuilder.skipped_columns.include? column.name.to_sym
end
end
# Collects association columns (relation columns) for the current class. Skips polymorphic
# associations because we can't guess which class to use for an automatically generated input.
def association_columns
model.reflect_on_all_associations(:belongs_to).select do |association_reflection|
association_reflection.options[:polymorphic] != true
end
end
def save_to_clipboard(data)
return unless data
begin
case RUBY_PLATFORM
when /win32/
require 'win32/clipboard'
::Win32::Clipboard.data = data
when /darwin/ # mac
`echo "#{data}" | pbcopy`
else # linux/unix
`echo "#{data}" | xsel --clipboard` || `echo "#{data}" | xclip`
end
rescue LoadError
false
else
true
end
end
end
end
|
ryanfox1985/formtastic
|
spec/actions/generic_action_spec.rb
|
# encoding: utf-8
require 'spec_helper'
RSpec.describe 'InputAction::Base' do
# Most basic Action class to test Base
class ::GenericAction
include ::Formtastic::Actions::Base
def supported_methods
[:submit, :reset, :cancel]
end
def to_html
wrapper do
builder.submit(text, button_html)
end
end
end
include FormtasticSpecHelper
before do
@output_buffer = ''
mock_everything
end
describe 'wrapping HTML' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :foo => 'bah' }
))
end)
end
it 'should add the #foo id to the li' do
expect(output_buffer).to have_tag('li#post_submit_action')
end
it 'should add the .action and .generic_action classes to the li' do
expect(output_buffer).to have_tag('li.action.generic_action')
end
it 'should pass :wrapper_html HTML attributes to the wrapper' do
expect(output_buffer).to have_tag('li.action.generic_action[@foo="bah"]')
end
context "when a custom :id is provided" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :id => 'foo_bah_bing' }
))
end)
end
it "should use the custom id" do
expect(output_buffer).to have_tag('li#foo_bah_bing')
end
end
context "when a custom class is provided as a string" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :class => 'foo_bah_bing' }
))
end)
end
it "should add the custom class strng to the existing classes" do
expect(output_buffer).to have_tag('li.action.generic_action.foo_bah_bing')
end
end
context "when a custom class is provided as an array" do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:wrapper_html => { :class => ['foo_bah_bing', 'zing_boo'] }
))
end)
end
it "should add the custom class strng to the existing classes" do
expect(output_buffer).to have_tag('li.action.generic_action.foo_bah_bing.zing_boo')
end
end
end
describe 'button HTML' do
before do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic,
:button_html => { :foo => 'bah' }
))
end)
end
it 'should pass :button_html HTML attributes to the button' do
expect(output_buffer).to have_tag('li.action.generic_action input[@foo="bah"]')
end
it 'should respect a default_commit_button_accesskey configuration with nil' do
with_config :default_commit_button_accesskey, nil do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
end)
expect(output_buffer).not_to have_tag('li.action input[@accesskey]')
end
end
it 'should respect a default_commit_button_accesskey configuration with a String' do
with_config :default_commit_button_accesskey, 's' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
end)
expect(output_buffer).to have_tag('li.action input[@accesskey="s"]')
end
end
it 'should respect an accesskey through options over configration' do
with_config :default_commit_button_accesskey, 's' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic, :accesskey => 'o'))
end)
expect(output_buffer).not_to have_tag('li.action input[@accesskey="s"]')
expect(output_buffer).to have_tag('li.action input[@accesskey="o"]')
end
end
end
describe 'labelling' do
describe 'when used without object' do
describe 'when explicit label is provided' do
it 'should render an input with the explicitly specified label' do
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic, :label => "Click!"))
concat(builder.action(:reset, :as => :generic, :label => "Reset!"))
concat(builder.action(:cancel, :as => :generic, :label => "Cancel!"))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Click!"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset!"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel!"]')
end
end
describe 'when no explicit label is provided' do
describe 'when no I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en, :formtastic => {
:submit => 'Submit %{model}',
:reset => 'Reset %{model}',
:cancel => 'Cancel %{model}',
:actions => {
:message => {
:submit => 'Submit message',
:reset => 'Reset message',
:cancel => 'Cancel message'
}
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with default I18n-localized label (fallback)' do
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Submit Post"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel Post"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset Post"]')
end
it 'should render an input with custom resource name localized label' do
concat(semantic_form_for(:post, :as => :message, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Submit message"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel message"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset message"]')
end
end
describe 'when I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:submit => 'Custom Submit',
:reset => 'Custom Reset',
:cancel => 'Custom Cancel'
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with localized label (I18n)' do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:post => {
:submit => 'Custom Submit %{model}',
:reset => 'Custom Reset %{model}',
:cancel => 'Custom Cancel %{model}'
}
}
}
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Submit Post"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Reset Post"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Cancel Post"]})
end
end
it 'should render an input with anoptional localized label (I18n) - if first is not set' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(:post, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Submit"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Reset"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Cancel"]})
end
end
end
end
end
describe 'when used on a new record' do
before do
allow(@new_post).to receive(:new_record?).and_return(true)
end
describe 'when explicit label is provided' do
it 'should render an input with the explicitly specified label' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic, :label => "Click!"))
concat(builder.action(:reset, :as => :generic, :label => "Reset!"))
concat(builder.action(:cancel, :as => :generic, :label => "Cancel!"))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Click!"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset!"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel!"]')
end
end
describe 'when no explicit label is provided' do
describe 'when no I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en, :formtastic => {
:create => 'Create %{model}',
:reset => 'Reset %{model}',
:cancel => 'Cancel %{model}'
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with default I18n-localized label (fallback)' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Create Post"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset Post"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel Post"]')
end
end
describe 'when I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:create => 'Custom Create',
:reset => 'Custom Reset',
:cancel => 'Custom Cancel'
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with localized label (I18n)' do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:post => {
:create => 'Custom Create %{model}',
:reset => 'Custom Reset %{model}',
:cancel => 'Custom Cancel %{model}'
}
}
}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Create Post"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Reset Post"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Cancel Post"]})
end
end
it 'should render an input with anoptional localized label (I18n) - if first is not set' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Create"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Reset"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Cancel"]})
end
end
end
end
end
describe 'when used on an existing record' do
before do
allow(@new_post).to receive(:persisted?).and_return(true)
end
describe 'when explicit label is provided' do
it 'should render an input with the explicitly specified label' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic, :label => "Click!"))
concat(builder.action(:reset, :as => :generic, :label => "Reset!"))
concat(builder.action(:cancel, :as => :generic, :label => "Cancel!"))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Click!"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset!"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel!"]')
end
end
describe 'when no explicit label is provided' do
describe 'when no I18n-localized label is provided' do
before do
::I18n.backend.store_translations :en, :formtastic => {
:update => 'Save %{model}',
:reset => 'Reset %{model}',
:cancel => 'Cancel %{model}',
:actions => {
:message => {
:submit => 'Submit message',
:reset => 'Reset message',
:cancel => 'Cancel message'
}
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with default I18n-localized label (fallback)' do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Save Post"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset Post"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel Post"]')
end
it 'should render an input with custom resource name localized label' do
concat(semantic_form_for(:post, :as => :message, :url => 'http://example.com') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag('li.generic_action input[@value="Submit message"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Cancel message"]')
expect(output_buffer).to have_tag('li.generic_action input[@value="Reset message"]')
end
end
describe 'when I18n-localized label is provided' do
before do
::I18n.backend.reload!
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:update => 'Custom Save',
:reset => 'Custom Reset',
:cancel => 'Custom Cancel'
}
}
end
after do
::I18n.backend.reload!
end
it 'should render an input with localized label (I18n)' do
with_config :i18n_lookups_by_default, true do
::I18n.backend.store_translations :en,
:formtastic => {
:actions => {
:post => {
:update => 'Custom Save %{model}',
:reset => 'Custom Reset %{model}',
:cancel => 'Custom Cancel %{model}'
}
}
}
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Save Post"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Reset Post"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Cancel Post"]})
end
end
it 'should render an input with anoptional localized label (I18n) - if first is not set' do
with_config :i18n_lookups_by_default, true do
concat(semantic_form_for(@new_post) do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Save"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Reset"]})
expect(output_buffer).to have_tag(%Q{li.generic_action input[@value="Custom Cancel"]})
::I18n.backend.store_translations :en, :formtastic => {}
end
end
end
end
end
end
describe 'when the model is two words' do
before do
output_buffer = ''
class ::UserPost
extend ActiveModel::Naming if defined?(ActiveModel::Naming)
include ActiveModel::Conversion if defined?(ActiveModel::Conversion)
def id
end
def persisted?
end
# Rails does crappy human_name
def self.human_name
"User post"
end
end
@new_user_post = ::UserPost.new
allow(@new_user_post).to receive(:new_record?).and_return(true)
concat(semantic_form_for(@new_user_post, :url => '') do |builder|
concat(builder.action(:submit, :as => :generic))
concat(builder.action(:reset, :as => :generic))
concat(builder.action(:cancel, :as => :generic))
end)
end
it "should render the string as the value of the button" do
expect(output_buffer).to have_tag('li input[@value="Create User post"]')
expect(output_buffer).to have_tag('li input[@value="Reset User post"]')
expect(output_buffer).to have_tag('li input[@value="Cancel User post"]')
end
end
end
|
ryanfox1985/formtastic
|
sample/config.ru
|
module Rack
module Formtastic
class Samples
def initialize(app)
@app = app
end
def call(env)
@status, @headers, @body = @app.call(env)
@env = env
@body = '' if favicon?
@body = static_file if !favicon? && static_file?
@body = stylesheet if stylesheet?
@headers ||= {}
@headers['Content-Type'] = mime(extension)
[@status, @headers, @body]
end
def static_file?
!stylesheet?
end
def stylesheet?
@env["PATH_INFO"] =~ /\.(css)/
end
def favicon?
@env["PATH_INFO"] =~ /favicon.ico$/
end
def extension
@env["PATH_INFO"].split(".").last
end
def mime(extension)
mimes[extension] || mimes['html']
end
def mimes
{
'ico' => 'image/x-icon',
'html' => 'text/html',
'css' => 'text/css',
'js' => 'text/javascript'
}
end
def static_file
::File.open(file_path)
end
def stylesheet
::File.open(::File.join("../app/assets/stylesheets", file_path))
end
def file_path
@env["PATH_INFO"].gsub(/^\//, '').gsub(/^$/, 'index.html')
end
end
end
end
use Rack::ContentLength
use Rack::Formtastic::Samples
app = lambda { |env| [200, @headers, @body] }
run app
|
ryanfox1985/formtastic
|
spec/support/specialized_class_finder_shared_example.rb
|
<reponame>ryanfox1985/formtastic
# encoding: utf-8
#
RSpec.shared_examples 'Specialized Class Finder' do
let(:builder) { Formtastic::FormBuilder.allocate }
subject(:finder) { described_class.new(builder) }
context 'by default' do
it 'includes Object and the default namespaces' do
expect(finder.namespaces).to eq([Object, default])
end
end
context 'with namespace configuration set to a custom list of modules' do
before do
stub_const('CustomModule', Module.new)
stub_const('AnotherModule', Module.new)
allow(Formtastic::FormBuilder).to receive(namespaces_setting)
.and_return([ CustomModule, AnotherModule ])
end
it 'includes just the custom namespaces' do
expect(finder.namespaces).to eq([CustomModule, AnotherModule])
end
end
end
|
ryanfox1985/formtastic
|
spec/builder/error_proc_spec.rb
|
# encoding: utf-8
require 'spec_helper'
RSpec.describe 'Rails field_error_proc' do
include FormtasticSpecHelper
before do
@output_buffer = ''
mock_everything
end
it "should not be overridden globally for all form builders" do
current_field_error_proc = ::ActionView::Base.field_error_proc
semantic_form_for(@new_post) do |builder|
expect(::ActionView::Base.field_error_proc).not_to eq(current_field_error_proc)
end
expect(::ActionView::Base.field_error_proc).to eq(current_field_error_proc)
form_for(@new_post) do |builder|
expect(::ActionView::Base.field_error_proc).to eq(current_field_error_proc)
end
end
end
|
matthijsgroen/game-of-geese
|
lib/gosu-formatter/listeners/pawn_listener.rb
|
# tell gosu when pawn is moved
module PawnListener
attr_accessor :formatter_listener
def location=(_value)
super.tap { formatter_listener.update }
end
end
|
matthijsgroen/game-of-geese
|
spec/models/rules/well_spec.rb
|
require 'spec_helper'
describe Rules::Well do
let(:game) { Game.new }
let(:board) { Board.new 40 }
let(:die) { FixedDie.new 5 }
let(:pawn) { Pawn.new color: :blue }
let(:person) { Person.new age: 8 }
before do
game.board = board
game.die = die
game.join person, pawn
end
it 'moves the player when 6 is rolled' do
game.set_rules_for_space described_class.new, 5
# Arrive on space with well
game.active_player.play_turn(die)
game.active_player.play_turn(FixedDie.new 6)
expect(pawn.location).to eql(11)
end
it 'locks the player for die values other than 6' do
game.set_rules_for_space described_class.new, 5
# Arrive on space with well
game.active_player.play_turn(die)
(1...5).each do |roll_value|
game.active_player.play_turn(FixedDie.new roll_value)
expect(pawn.location).to eql(5)
end
end
end
|
matthijsgroen/game-of-geese
|
features/support/helpers/game_helpers.rb
|
# Helper methods to ease setting up the game
module GameHelpers
def add_player(game, attributes)
person_attributes = attributes.select { |k| [:name, :age].include? k }
pawn_attributes = attributes.select { |k| [:color].include? k }
person = Person.new person_attributes
pawn = Pawn.new(pawn_attributes)
game.join(person, pawn)
end
end
World(GameHelpers)
|
matthijsgroen/game-of-geese
|
app/models/rules/well.rb
|
require_relative './base'
module Rules
# It locks the player in place
class Well < Base
def leave_space(pawn, die_value)
pawn.location += die_value if die_value == 6
end
end
end
|
matthijsgroen/game-of-geese
|
app/models/roles/player_circle.rb
|
# This role represents a circle of players,
# positioned clock-wise
module PlayerCircle
def start
# the youngest player may start
sort { |a, b| a.age <=> b.age }.first
end
def next_after(player)
player == last ? first : at(index(player) + 1)
end
def next_after_with_skipping(player)
loop do
player = next_after_without_skipping(player)
return player if player.allowed_to_play?
end
end
alias_method :next_after_without_skipping, :next_after
alias_method :next_after, :next_after_with_skipping
end
|
matthijsgroen/game-of-geese
|
spec/models/rules/skip_turn_spec.rb
|
<filename>spec/models/rules/skip_turn_spec.rb
require 'spec_helper'
describe Rules::SkipTurn do
let(:game) { Game.new }
let(:board) { Board.new 40 }
let(:die) { FixedDie.new 5 }
let(:pawn) { Pawn.new color: :blue }
let(:person) { Person.new age: 8 }
let(:second_person) { Person.new age: 9 }
let(:third_person) { Person.new age: 10 }
before do
game.board = board
game.die = die
game.join person, pawn
game.join second_person, Pawn.new(color: :red)
game.join third_person, Pawn.new(color: :white)
end
it 'lets a player skip a number of turns' do
game.set_rules_for_space described_class.new(1), 5
# Arrive on space with skip turn
game.active_player.play_turn(die)
expect(game.active_player).to eql(second_person)
game.active_player.play_turn(FixedDie.new 4)
expect(game.active_player).to eql(third_person)
# Other player moves
expect do
game.active_player.play_turn(FixedDie.new 4)
end.to change { game.active_player }.to(second_person)
end
end
|
matthijsgroen/game-of-geese
|
lib/gosu-formatter/remote_client.rb
|
<filename>lib/gosu-formatter/remote_client.rb<gh_stars>0
require_relative '../../app/models/board'
require_relative '../../app/models/die'
require_relative '../../app/models/game'
require_relative '../../app/models/pawn'
require_relative '../../app/models/person'
require_relative '../../app/models/roles/player_circle'
require_relative '../../app/models/roles/player'
require_relative './game_window'
require 'drb/drb'
window = GameWindow.new
DRb.start_service('druby://localhost:8787', window)
window.show
|
matthijsgroen/game-of-geese
|
lib/gosu-formatter/space_generator.rb
|
<gh_stars>0
# Generates locations for spaces on the Game of Goose board
class SpaceGenerator
DIRECTIONS = [:right, :down, :left, :up]
def initialize(max_x, max_y, row_spacing:, cell_spacing:)
@row_spacing = row_spacing
@cell_spacing = cell_spacing
set_boundaries(max_x, max_y)
@spaces = []
@direction = DIRECTIONS.first
@topleft = { x: 0, y: 0 }
end
attr_reader :spaces
def generate_spaces(count)
count.times do
@spaces << {
topleft_x: @topleft[:x],
topleft_y: @topleft[:y],
direction: @direction
}
draw_next_tile
end
end
private
def draw_next_tile
case @direction
when :right then draw_tile_right
when :down then draw_tile_down
when :left then draw_tile_left
when :up then draw_tile_up
end
end
def set_boundaries(max_x, max_y)
@boundaries = {
top: @row_spacing,
left: 0,
right: max_x,
bottom: max_y
}
end
def draw_tile_right
@topleft[:x] += @cell_spacing
when_out_of_boundaries do
@boundaries[:right] -= @row_spacing
end
end
def draw_tile_down
@topleft[:y] += @cell_spacing
when_out_of_boundaries do
@boundaries[:bottom] -= @row_spacing
end
end
def draw_tile_left
@topleft[:x] -= @cell_spacing
when_out_of_boundaries do
@boundaries[:left] += @row_spacing
end
end
def draw_tile_up
@topleft[:y] -= @cell_spacing
when_out_of_boundaries do
@boundaries[:top] += @row_spacing
end
end
def when_out_of_boundaries
return unless out_of_boundaries?
yield
next_direction
end
def out_of_boundaries?
case @direction
when :up then @topleft[:y] <= @boundaries[:top]
when :left then @topleft[:x] <= @boundaries[:left]
when :down then @topleft[:y] >= @boundaries[:bottom]
when :right then @topleft[:x] >= @boundaries[:right]
end
end
def next_direction
index = (DIRECTIONS.index(@direction) + 1) % DIRECTIONS.length
@direction = DIRECTIONS[index]
end
end
|
matthijsgroen/game-of-geese
|
spec/models/rules/goto_space_spec.rb
|
<reponame>matthijsgroen/game-of-geese
require 'spec_helper'
describe Rules::GotoSpace do
let(:game) { Game.new }
let(:board) { Board.new 40 }
let(:die) { FixedDie.new 5 }
let(:pawn) { Pawn.new color: :blue }
let(:person) { Person.new age: 8 }
before do
game.board = board
game.die = die
game.join person, pawn
end
it 'brings the player to a new location' do
game.set_rules_for_space described_class.new(18), 5
game.play_round
expect(pawn.location).to eql 18
end
it 'respects the rules of the new location' do
game.set_rules_for_space described_class.new(18), 5
game.set_rules_for_space described_class.new(10), 18
game.play_round
expect(pawn.location).to eql 10
end
end
|
matthijsgroen/game-of-geese
|
app/models/roles/board_pawn.rb
|
# A pawn that can move across a game board
module BoardPawn
attr_accessor :location
attr_accessor :board
end
|
matthijsgroen/game-of-geese
|
app/models/rules/skip_turn.rb
|
require_relative './base'
module Rules
# Brings the player to a new location
class SkipTurn < Base
def initialize(amount_turns_to_skip)
@amount_turns_to_skip = amount_turns_to_skip
@turns_skipped = 0
end
def allowed_to_roll?
@turns_skipped += 1
@turns_skipped > @amount_turns_to_skip
end
end
end
|
matthijsgroen/game-of-geese
|
lib/gosu-formatter/renderers/board_renderer.rb
|
<reponame>matthijsgroen/game-of-geese
# Renders the game board
class BoardRenderer
def initialize(window)
@window = window
@font = Gosu::Font.new(@window, Gosu.default_font_name, 20)
@rule_images = []
@default_image = Gosu::Image.new(@window, image_path('default'), true)
add_images_by_description
add_images_by_rule
end
def render_board(spaces, rules)
spaces.each_with_index do |space, index|
label = index
label = 'Start' if index == 0
color = COLOR_DEFAULT
rule = rules[index]
image = rule_image(rule)
image ||= @default_image if index % 3 == 0
color = COLOR_GREEN if rule
draw_space(label, space, color: color, image: image)
end
end
private
IMAGES_WITH_DESCRIPTION = {
'kerkhof' => 'dead',
'gevangenis' => 'jail',
'brug' => 'bridge',
'doolhof' => 'lost',
'hotel' => 'hotel',
'trap' => 'stairs',
'vogelkooi' => 'cage'
}
IMAGES_WITH_RULE = {
'RollAgain' => 'roll_again',
'Well' => 'well',
'Curvet' => 'curvet',
'GooseSpace' => 'goose'
}
def add_images_by_description
IMAGES_WITH_DESCRIPTION.each do |description, image|
add_image(image, description: description)
end
end
def add_images_by_rule
IMAGES_WITH_RULE.each do |rule, image|
add_image(image, rule: "Rules::#{rule}")
end
end
COLOR_DEFAULT = Gosu::Color.new(0xFFf8ec58)
COLOR_GREEN = Gosu::Color.new(0xFFf1ce4c)
def rule_image(rule)
return nil unless rule
rule_image = @rule_images.find do |i|
i[:description] == rule[:description]
end if rule[:description]
rule_image ||= @rule_images.find { |i| i[:rule] == rule[:rule] }
return nil unless rule_image
rule_image[:image]
end
def add_image(filename, attachment)
image_data = {
image: Gosu::Image.new(@window, image_path(filename), true)
}.merge attachment
@rule_images << image_data
end
def image_path(filename)
"app/images/spaces/#{filename}.jpg"
end
def draw_space(label, space, color: COLOR_DEFAULT, image: nil)
topleft_x = space[:topleft_x] - (space[:direction] == :left ? 9 : 0)
topleft_y = space[:topleft_y] - (space[:direction] == :up ? 9 : 0)
size_x = [:right, :left].include?(space[:direction]) ? 59 : 50
size_y = [:up, :down].include?(space[:direction]) ? 59 : 50
draw_square(topleft_x, topleft_y, size_x, size_y, color: color)
image.draw(topleft_x, topleft_y, 0) if image
@font.draw(label, topleft_x, topleft_y, 1, 1, 1, 0x40000000)
end
def draw_square(topleft_x, topleft_y, size_x, size_y, color: COLOR_DEFAULT)
@window.draw_quad(
topleft_x, topleft_y, color,
topleft_x + size_x, topleft_y, color,
topleft_x, topleft_y + size_y, color,
topleft_x + size_x, topleft_y + size_y, color,
0
)
end
end
|
matthijsgroen/game-of-geese
|
spec/models/rules/roll_again_spec.rb
|
<reponame>matthijsgroen/game-of-geese<filename>spec/models/rules/roll_again_spec.rb
require 'spec_helper'
describe Rules::RollAgain do
let(:game) { Game.new }
let(:board) { Board.new 40 }
let(:die) { FixedDie.new 5 }
let(:pawn) { Pawn.new color: :blue }
let(:person) { Person.new age: 8 }
let(:other_person) { Person.new age: 9 }
before do
game.board = board
game.die = die
game.join person, pawn
game.join other_person, Pawn.new(color: :red)
end
it 'lets the player roll again' do
game.set_rules_for_space described_class.new, 5
expect do
game.active_player.play_turn(die)
end.not_to change { game.active_player }
end
it 'respects a max set die value' do
rule = described_class.new
rule.max_die_value = 3
game.set_rules_for_space rule, 5
expect do
game.active_player.play_turn(die)
end.to change { game.active_player }
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.