repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
thamilton2014/chef-repo
|
cookbooks/phpcs/recipes/pear.rb
|
#
# Cookbook Name:: phpcs
# Recipe:: pear
#
# Copyright 2013-2014, Escape Studios
#
include_recipe "php"
#PHP Extension and Application Repository PEAR channel
pearhub_chan = php_pear_channel "pear.php.net" do
action :update
end
#upgrade PEAR
php_pear "PEAR" do
channel pearhub_chan.channel_name
action :upgrade
end
#PHPUnit PEAR channel
php_pear_channel "pear.phpunit.de" do
action :discover
end
#upgrade phpcs
php_pear "PHP_CodeSniffer" do
channel pearhub_chan.channel_name
if node['phpcs']['version'] != "latest"
version "#{node['phpcs']['version']}"
end
action :upgrade if node['phpcs']['version'] == "latest"
end
|
thamilton2014/chef-repo
|
roles/selenium.rb
|
name 'selenium'
description 'This role applies selenium hub recipes to a server'
hub_env = [
'recipe[start-hub]'
]
node_env = [
'recipe[start-node]'
]
default_env = [
]
env_run_lists(
'_default' => default_env,
'hub' => hub_env,
'node' => node_env
)
|
thamilton2014/chef-repo
|
cookbooks/start-node/recipes/default.rb
|
#
# Cookbook Name:: start-node
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
version = '2.44'
selenium = "selenium-server-standalone-#{version}.0.jar"
server = 'http://10.44.73.64:4444/grid/register'
mac_chrome_driver = 'chromedriver'
mac_safari_driver = '/Applications/Safari.app/Contents/MacOS/Safari'
win_chrome_driver = 'chromedriver_win.exe'
win_ie_driver = 'IEDriverServer.exe'
if platform_family? 'mac_os_x'
selenium_dir = '/Users/administrator/selenium/'
directory selenium_dir do
user 'administrator'
action :create
end
cookbook_file selenium do
path "#{selenium_dir}/#{selenium}"
action :create_if_missing
end
cookbook_file mac_chrome_driver do
path "/usr/bin/#{mac_chrome_driver}"
action :create_if_missing
end
execute 'Execute selenium server' do
cwd selenium_dir
command "java -Dwebdriver.chrome.driver=#{mac_chrome_driver} -jar #{selenium} -role node -hub #{server} &"
not_if 'ps aux | grep "[s]elenium"'
action :run
end
elsif platform_family? 'windows'
selenium_dir = "C:\\Users\\Administrator\\Desktop\\selenium\\"
directory selenium_dir do
action :create
end
cookbook_file selenium do
path "#{selenium_dir}\\#{selenium}"
action :create_if_missing
end
cookbook_file win_chrome_driver do
path "#{selenium_dir}\\#{win_chrome_driver}"
action :create_if_missing
end
cookbook_file win_ie_driver do
path "#{selenium_dir}\\#{win_ie_driver}"
action :create_if_missing
end
execute 'Execute selenium server' do
cwd selenium_dir
command "java -Dwebdriver.chrome.driver=#{win_chrome_driver} -Dwebdriver.ie.driver=#{win_ie_driver}-jar #{selenium} -role node -hub #{server}"
action :run
end
elsif platform_family? 'linux'
echo 'Not implemented yet...'
else
print 'Platform not supported'
end
|
thamilton2014/chef-repo
|
cookbooks/phpcs/attributes/composer.rb
|
#
# Cookbook Name:: phpcs
# Attributes:: composer
#
# Copyright 2013-2014, Escape Studios
#
default['phpcs']['prefix'] = "/usr/bin"
|
thamilton2014/chef-repo
|
cookbooks/composer/attributes/default.rb
|
#
# Cookbook Name:: composer
# Attributes:: default
#
# Copyright 2012-2014, Escape Studios
#
include_attribute 'php'
if node['platform'] == 'windows'
default['composer']['url'] = 'https://getcomposer.org/Composer-Setup.exe'
default['composer']['install_dir'] = 'C:\\ProgramData\\ComposerSetup'
default['composer']['bin'] = "#{node['composer']['install_dir']}\\composer.bat"
else
default['composer']['url'] = 'http://getcomposer.org/composer.phar'
default['composer']['install_dir'] = '/usr/local/bin'
default['composer']['bin'] = "#{node['composer']['install_dir']}/composer"
default['composer']['install_globally'] = true
default['composer']['mask'] = 0755
default['composer']['link_type'] = :symbolic
end
default['composer']['global_configs'] = {}
default['composer']['home_dir'] = nil
default['composer']['php_recipe'] = 'php::default'
|
thamilton2014/chef-repo
|
cookbooks/myairwatch/recipes/default.rb
|
<filename>cookbooks/myairwatch/recipes/default.rb
#
# Cookbook Name:: myairwatch
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
file = 'sharedlibs-unit_tests-lastest.tar'
repo = "http://10.44.72.81:8081/artifactory/sharedlibs/#{file}"
folder = '/opt/myairwatch/'
directory folder do
user 'root'
action :create
end
remote_file "#{folder}/#{file}" do
source repo
end
execute 'Install sharedlibs' do
cwd folder
command "tar -xvf #{file}"
action :run
end
cookbook_file 'phpinfo.php' do
path '/var/www/html/phpinfo.php'
action :create_if_missing
end
execute 'Configure sites-enables' do
command 'cp /etc/httpd/sites-available/default.conf /etc/httpd/sites-enabled/'
action :run
end
execute 'Cheating by turning off iptables... should be configured though...' do
command 'service iptables stop'
action :run
end
execute 'Cheating by flushing iptables... for extra measure, you know?' do
command 'iptables -F'
action :run
end
|
thamilton2014/chef-repo
|
cookbooks/pdepend/recipes/composer.rb
|
<filename>cookbooks/pdepend/recipes/composer.rb
#
# Cookbook Name:: pdepend
# Recipe:: composer
#
# Copyright 2013, Escape Studios
#
include_recipe "composer"
pdepend_dir = "#{Chef::Config[:file_cache_path]}/pdepend"
directory "#{pdepend_dir}" do
owner "root"
group "root"
mode "0755"
action :create
end
#figure out what version to install
if node[:pdepend][:version] != "latest"
version = node[:pdepend][:version]
else
version = "*.*.*"
end
#composer.json
template "#{pdepend_dir}/composer.json" do
source "composer.json.erb"
owner "root"
group "root"
mode 0600
variables(
:version => version,
:bindir => node[:pdepend][:prefix]
)
end
#composer update
execute "pdepend-composer" do
user "root"
cwd pdepend_dir
command "composer update"
action :run
end
|
thamilton2014/chef-repo
|
cookbooks/pdepend/recipes/phar.rb
|
#
# Cookbook Name:: pdepend
# Recipe:: phar
#
# Copyright 2013, Escape Studios
#
if node[:pdepend][:install_dir] != ""
pdepend_dir = node[:pdepend][:install_dir]
else
pdepend_dir = "#{Chef::Config[:file_cache_path]}/pdepend"
end
directory "#{pdepend_dir}" do
owner "root"
group "root"
mode "0755"
action :create
end
remote_file "#{pdepend_dir}/pdepend.phar" do
source node[:pdepend][:phar_url]
mode "0755"
end
|
thamilton2014/chef-repo
|
cookbooks/phpmd/attributes/default.rb
|
#
# Cookbook Name:: phpmd
# Attributes:: default
#
# Copyright 2013, Escape Studios
#
default[:phpmd][:install_method] = "pear"
default[:phpmd][:version] = "latest"
|
thamilton2014/chef-repo
|
environments/hub.rb
|
<gh_stars>0
name "hub"
description "The selenium hub environment"
|
thamilton2014/chef-repo
|
cookbooks/myairwatch-install-user/recipes/default.rb
|
#
# Cookbook Name:: myairwatch-install-user
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
users = {
:thamilton => '<NAME>'
}
users.each do |username, fullname|
execute 'Installing users' do
command "adduser #{username}"
not_if "cat /etc/passwd | grep #{username}"
action :run
end
directory "/home/#{username}/.ssh" do
owner "#{username}"
group "#{username}"
mode '0755'
action :create
end
cookbook_file "#{username}.pub" do
owner "#{username}"
group "#{username}"
mode '0755'
path "/home/#{username}/.ssh/#{username}.pub"
action :create_if_missing
end
file "/home/#{username}/.ssh/authorized_keys" do
owner "#{username}"
group "#{username}"
mode '0700'
action :create_if_missing
end
execute 'Adding user to authorized_keys' do
command "cat /home/#{username}/.ssh/#{username}.pub >> /home/#{username}/.ssh/authorized_keys"
action :run
end
execute 'Add user to wheel' do
command "usermod -a -G wheel #{username}"
action :run
end
end
execute 'Restarting sshd' do
command '/etc/init.d/sshd restart'
action :run
end
|
thamilton2014/chef-repo
|
cookbooks/phpmd/recipes/default.rb
|
<reponame>thamilton2014/chef-repo
#
# Cookbook Name:: phpmd
# Recipe:: default
#
# Copyright 2013, Escape Studios
#
case node[:phpmd][:install_method]
when "pear"
include_recipe "phpmd::pear"
when "composer"
include_recipe "phpmd::composer"
when "phar"
include_recipe "phpmd::phar"
end
|
thamilton2014/chef-repo
|
cookbooks/pdepend/metadata.rb
|
<reponame>thamilton2014/chef-repo<filename>cookbooks/pdepend/metadata.rb
name "pdepend"
maintainer "Escape Studios"
maintainer_email "<EMAIL>"
license "MIT"
description "Installs/Configures pdepend"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "0.0.4"
%w{ debian ubuntu redhat centos fedora scientific amazon }.each do |os|
supports os
end
depends "php"
depends "composer"
recipe "pdepend", "Installs pdepend."
recipe "pdepend::composer", "Installs pdepend using composer."
recipe "pdepend::pear", "Installs pdepend using pear."
recipe "pdepend::phar", "Installs pdepend using phar."
|
thamilton2014/chef-repo
|
cookbooks/phpmd/attributes/phar.rb
|
<reponame>thamilton2014/chef-repo
#
# Cookbook Name:: phpmd
# Attributes:: phar
#
# Copyright 2013, Escape Studios
#
default[:phpmd][:phar_url] = "http://static.phpmd.org/php/latest/phpmd.phar"
default[:phpmd][:install_dir] = ""
|
thamilton2014/chef-repo
|
cookbooks/phpmd/metadata.rb
|
<gh_stars>0
name "phpmd"
maintainer "Escape Studios"
maintainer_email "<EMAIL>"
license "MIT"
description "Installs/Configures phpmd"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "0.0.5"
%w{ debian ubuntu redhat centos fedora scientific amazon }.each do |os|
supports os
end
depends "php"
depends "composer"
depends "pdepend"
recipe "phpmd", "Installs phpmd."
recipe "phpmd::composer", "Installs phpmd using composer."
recipe "phpmd::pear", "Installs phpmd using pear."
recipe "phpmd::phar", "Installs phpmd using phar."
|
thamilton2014/chef-repo
|
cookbooks/start-hub/recipes/default.rb
|
<filename>cookbooks/start-hub/recipes/default.rb
#
# Cookbook Name:: start-hub
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
version = '2.44'
selenium = "selenium-server-standalone-#{version}.0.jar"
selenium_dir = '/opt/selenium'
directory selenium_dir do
action :create
end
cookbook_file selenium do
path "#{selenium_dir}/#{selenium}"
action :create_if_missing
end
execute 'Execute selenium server' do
cwd selenium_dir
command "java -jar #{selenium} -role hub &"
not_if 'ps aux | grep "[s]elenium"'
action :run
end
|
thamilton2014/chef-repo
|
environments/dev.rb
|
<reponame>thamilton2014/chef-repo
name "dev"
description "The development environment"
|
thamilton2014/chef-repo
|
cookbooks/phpcs/recipes/default.rb
|
<filename>cookbooks/phpcs/recipes/default.rb
#
# Cookbook Name:: phpcs
# Recipe:: default
#
# Copyright 2013-2014, Escape Studios
#
case node['phpcs']['install_method']
when "pear"
include_recipe "phpcs::pear"
when "composer"
include_recipe "phpcs::composer"
end
include_recipe "phpcs::coding-standard"
|
thamilton2014/chef-repo
|
cookbooks/phpmd/recipes/phar.rb
|
<reponame>thamilton2014/chef-repo
#
# Cookbook Name:: phpmd
# Recipe:: phar
#
# Copyright 2013, Escape Studios
#
include_recipe "pdepend::phar"
if node[:phpmd][:install_dir] != ""
phpmd_dir = node[:phpmd][:install_dir]
else
phpmd_dir = "#{Chef::Config[:file_cache_path]}/phpmd"
end
directory "#{phpmd_dir}" do
owner "root"
group "root"
mode "0755"
action :create
end
remote_file "#{phpmd_dir}/phpmd.phar" do
source node[:phpmd][:phar_url]
mode "0755"
end
|
thamilton2014/chef-repo
|
cookbooks/phpmd/recipes/pear.rb
|
#
# Cookbook Name:: phpmd
# Recipe:: pear
#
# Copyright 2013, Escape Studios
#
include_recipe "php"
include_recipe "pdepend::pear"
#PHP Extension and Application Repository PEAR channel
pearhub_chan = php_pear_channel "pear.php.net" do
action :update
end
#upgrade PEAR
php_pear "PEAR" do
channel pearhub_chan.channel_name
action :upgrade
end
#phpmd PEAR channel
pearhub_chan = php_pear_channel "pear.phpmd.org" do
action :discover
end
#upgrade phpmd
php_pear "PHP_PMD" do
channel pearhub_chan.channel_name
if node[:phpmd][:version] != "latest"
version "#{node[:phpmd][:version]}"
end
action :upgrade if node[:phpmd][:version] == "latest"
end
|
thamilton2014/chef-repo
|
cookbooks/phpcs/attributes/coding-standard.rb
|
<reponame>thamilton2014/chef-repo
#
# Cookbook Name:: phpcs
# Attributes:: coding-standard
#
# Copyright 2013-2014, Escape Studios
#
default['phpcs']['coding_standards'] = {}
|
thamilton2014/chef-repo
|
cookbooks/pdepend/recipes/pear.rb
|
#
# Cookbook Name:: pdepend
# Recipe:: pear
#
# Copyright 2013, Escape Studios
#
include_recipe "php"
#PHP Extension and Application Repository PEAR channel
php_pear_channel "pear.php.net" do
action :update
end
#upgrade PEAR
php_pear "PEAR" do
action :upgrade
end
#pdepend PEAR channel
pearhub_chan = php_pear_channel "pear.pdepend.org" do
action :discover
end
#upgrade pdepend
php_pear "PHP_Depend-beta" do
channel pearhub_chan.channel_name
if node[:pdepend][:version] != "latest"
version "#{node[:pdepend][:version]}"
end
action :upgrade if node[:pdepend][:version] == "latest"
end
|
thamilton2014/chef-repo
|
roles/base.rb
|
name "base"
description 'Base role applied to all nodes'
run_list(
'recipe[git]',
'recipe[build-essential]',
'recipe[myairwatch-install-user]'
)
|
thamilton2014/chef-repo
|
cookbooks/phpmd/attributes/composer.rb
|
#
# Cookbook Name:: phpmd
# Attributes:: composer
#
# Copyright 2013, Escape Studios
#
default[:phpmd][:prefix] = "/usr/bin"
|
thamilton2014/chef-repo
|
cookbooks/myairwatch/metadata.rb
|
name 'myairwatch'
maintainer 'YOUR_COMPANY_NAME'
maintainer_email 'YOUR_EMAIL'
license 'All rights reserved'
description 'Installs/Configures myairwatch'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
|
thamilton2014/chef-repo
|
cookbooks/phpmd/recipes/composer.rb
|
#
# Cookbook Name:: phpmd
# Recipe:: composer
#
# Copyright 2013, Escape Studios
#
include_recipe "composer"
include_recipe "pdepend::composer"
phpmd_dir = "#{Chef::Config[:file_cache_path]}/phpmd"
directory "#{phpmd_dir}" do
owner "root"
group "root"
mode "0755"
action :create
end
#figure out what version to install
if node[:phpmd][:version] != "latest"
version = node[:phpmd][:version]
else
version = "*.*.*"
end
#composer.json
template "#{phpmd_dir}/composer.json" do
source "composer.json.erb"
owner "root"
group "root"
mode 0600
variables(
:version => version,
:bindir => node[:phpmd][:prefix]
)
end
#composer update
execute "phpmd-composer" do
user "root"
cwd phpmd_dir
command "composer update"
action :run
end
|
jonpearse/simple_ar_localization
|
lib/simple_ar_localizer.rb
|
require 'simple_ar_localizer/version'
require 'simple_ar_localizer/map'
require 'simple_ar_localizer/localizer'
module SimpleARLocalizer
# Convenience accessort to SimpleARLocalizer::Localizer::transform()
def self.transform( model_name, language, l10n_data )
Localizer.transform( model_name, language, l10n_data )
end
end
|
jonpearse/simple_ar_localization
|
lib/simple_ar_localizer/version.rb
|
module SimpleARLocalizer
VERSION = '1.0.1'
end
|
jonpearse/simple_ar_localization
|
lib/simple_ar_localizer/localizer.rb
|
<filename>lib/simple_ar_localizer/localizer.rb
require 'singleton'
module SimpleARLocalizer
# Localizer provides a slightly easier way of hooking into the depths of Rails’ Internationalization functionality.
#
# By default, it allows you to specify the human name (with plurality), human attribute names, and any custom error messages
# on both a per-model and per-attribute level via a simple hash… rather than having to worry about exactly where things
# get nested in .YAML files.
#
# It takes a bit of explaining to start with, but should be way nicer in the long-run =)
class Localizer
include Singleton
# Constructor logic. This should not be called directly.
def initialize
@custom_rules = {}
# if we have a custom startup hook
if defined?( Rails ) and Rails.application.config.respond_to?( :ar_localization_rules )
@custom_rules = Rails.application.config.ar_localization_rules
end
end
# Does the actual translation from the nicely-formatted hash, to a more Rails i18n-friendly one.
#
# === Parameters
#
# [model_name] the model we’re specifying localisations for
# [language] the ISO-639 language code of the language we’re providing a localisation for
# [L10n_data] a hash containing localisation data for the model/language combination
def self.transform( model_name, language, l10n_data )
self.instance.send( :perform_translation, model_name, language, l10n_data )
end
protected
# Callback from self.transform that actually does the work.
#
# === Parameters
#
# [model_name] the model we’re specifying localisations for
# [language] the ISO-639 language code of the language we’re providing a localisation for
# [L10n_data] a hash containing localisation data for the model/language combination
def perform_translation( model_name, language, l10n_data )
# normalise the model name
model_name = model_name.name.underscore.to_sym if model_name.is_a?( Class )
# normalise the language, while we’re at it
language = language.to_sym unless language.is_a?( Symbol )
# compile our rules into a tree for easier matching
@rules = SimpleARLocalizer::DEFAULT_MAP.merge( @custom_rules ).deep_stringify_keys
# parse everything
parsed = deep_parse( l10n_data.deep_stringify_keys, { model: model_name })
# squish it out to a hash
hsh = {}
parsed.each{ |k,v| deep_assign( hsh, k, v ) }
# drop in the language and return
retval = {}
retval[language] = hsh
retval
end
# Performs the grunt work of recursing through the inbound array and turning it into a hash where keys are the
# dotted internationalization keys, and the values are the translated value for that key.
#
# === Parameters
#
# [data_in] the current level of the hash to parse
# [replacements] a hash containing values of tokens that should be replaced when generating internationalization keys
# [curr_path] the current path within the hash for use when looking up mapping values
def deep_parse( data_in, replacements, curr_path = '' )
# start a return value
retval = {}
# find some rules that match at this level
local_paths = @rules.keys
local_paths.select!{ |p| p.starts_with?( curr_path ) } unless curr_path.blank?
# finally, strip off any trailing stuff so we only have the current stub, then sort them so wildcards go at the end
local_paths = local_paths.map{ |p| p.gsub(curr_path, '').gsub(/\/(.*)/, '') }.uniq.sort.reverse
# now, stash some replacements somewhere
local_replacements = replacements.dup
# start iterating through keys at this level
data_in.each do |key, value|
# search for candidates
candidates = local_paths.select{ |p| ((p === key) or p.starts_with?( ':' )) }
next if candidates.empty?
matched_path = candidates.first
# if we’ve matched a symbol
local_replacements[matched_path[1..-1].to_sym] = key if matched_path.starts_with?( ':' )
# if it’s a hash, recurse
if value.is_a?( Hash )
retval.merge!( deep_parse( value, local_replacements, "#{curr_path}#{matched_path}/" ))
else
# do some substitution + cast to an array (so we can do multiple at once)
full_rule = @rules["#{curr_path}#{matched_path}"]
full_rule = [ full_rule ] unless full_rule.is_a?( Array )
# and then…
full_rule.each do |r|
# allow passing in more complex rules as hashes
if r.is_a?( Hash )
value = r['proc'].call( value )
r = r['key']
end
# write it to the array
retval[ r.gsub( /%\{(\w+)\}/ ){ |m| local_replacements[ $1.to_sym ] }] = value
end
end
end
# return the result
retval
end
def deep_assign( hsh, key, data )
# prepare for some recursion fun
target = hsh
path = key.to_s.split( '.' ).map( &:to_sym )
final = path.pop
# unravel stuff a bit
path.each do |k|
target[k] = {} unless target.key?( k )
target = target[k]
end
# push the final data…
target[final] = data
# … + return
hsh
end
end
end
|
jonpearse/simple_ar_localization
|
lib/simple_ar_localizer/map.rb
|
module SimpleARLocalizer
# Default mapping from inbound localisation data to I18n keys. These can be supplemented/overridden via the
# <tt>Rails.application.config.ar_localization_rules</tt> configuration variable.
DEFAULT_MAP = {
# per-model stuff
'name': 'activerecord.models.%{model}',
'name/singular': 'activerecord.models.%{model}.one',
'name/plural': 'activerecord.models.%{model}.other',
'name/:key': 'activerecord.models.%{model}.%{key}',
'errors/:error': 'activerecord.errors.models.%{model}.%{error}',
# per-attribute stuff
'attributes/:attr': 'activerecord.attributes.%{model}.%{attr}', # only specifying a name
'attributes/:attr/name': 'activerecord.attributes.%{model}.%{attr}', # verbose specification
'attributes/:attr/errors/:error': 'activerecord.errors.models.%{model}.attributes.%{attr}.%{error}'
}
end
|
jonpearse/simple_ar_localization
|
simple_ar_localizer.gemspec
|
<filename>simple_ar_localizer.gemspec<gh_stars>0
# encoding: UTF-8
require File.expand_path('../lib/simple_ar_localizer/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'simple_ar_localizer'
gem.summary = 'Easier localisation for ActiveRecord models.'
gem.description = 'Provides a (hopefully) simpler way of localising the human name, attribute names, and error message for ActiveRecord models.'
gem.version = SimpleARLocalizer::VERSION
gem.files = `git ls-files`.split($\)
gem.require_paths = [ 'lib' ]
gem.authors = '<NAME>'
gem.email = '<EMAIL>'
gem.license = 'MIT'
gem.homepage = 'https://github.com/jonpearse/simple_ar_localizer'
gem.add_dependency( 'activerecord', '>= 5.1' )
end
|
espen/zoom_rb
|
lib/zoom/actions/sip_audio.rb
|
# frozen_string_literal: true
module Zoom
module Actions
module SipAudio
def sip_trunks_get(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id)
Utils.parse_response self.class.get("/accounts/#{params[:account_id]}/sip_trunk/trunks", headers: request_headers)
end
def sip_trunks_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id, :trunk_id)
Utils.parse_response self.class.delete("/accounts/#{params[:account_id]}/sip_trunk/trunks/#{params[:trunk_id]}", headers: request_headers)
end
def sip_trunk_numbers_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id)
Utils.parse_response self.class.delete("/accounts/#{params[:account_id]}/sip_trunk/numbers", headers: request_headers)
end
def sip_trunks_internal_numbers_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[account_id number_id])
Utils.parse_response self.class.delete("/accounts/#{params[:account_id]}/sip_trunk/internal_numbers/#{params[:number_id]}", headers: request_headers)
end
def sip_trunks_internal_callout_country_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[account_id country_id])
Utils.parse_response self.class.delete("/accounts/#{params[:account_id]}/sip_trunk/callout_countries/#{params[:country_id]}", headers: request_headers)
end
def sip_trunks_internal_numbers_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id).permit(%i[page_size next_page_token])
response = self.class.get("/accounts/#{params[:account_id]}/sip_trunk/internal_numbers", query: params, headers: request_headers)
Utils.parse_response(response)
end
def sip_trunks_internal_callout_country_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id)
response = self.class.get("/accounts/#{params[:account_id]}/sip_trunk/callout_countries", headers: request_headers)
Utils.parse_response(response)
end
def sip_trunks_numbers_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
response = self.class.get("/sip_trunk/numbers", headers: request_headers)
Utils.parse_response(response)
end
def sip_trunks_internal_numbers_add(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id)
Utils.parse_response self.class.post("/accounts/#{params[:account_id]}/sip_trunk/internal_numbers", headers: request_headers)
end
def sip_trunks_internal_callout_countries_add(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id)
Utils.parse_response self.class.post("/accounts/#{params[:account_id]}/sip_trunk/callout_countries", headers: request_headers)
end
def sip_trunks_numbers_assign(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:account_id)
Utils.parse_response self.class.post("/accounts/#{params[:account_id]}/sip_trunk/numbers", headers: request_headers)
end
end
end
end
|
espen/zoom_rb
|
lib/zoom/actions/webinar.rb
|
<reponame>espen/zoom_rb
# frozen_string_literal: true
module Zoom
module Actions
module Webinar
RECURRENCE_KEYS = %i[type repeat_interval weekly_days monthly_day monthly_week
monthly_week_day end_times end_date_time].freeze
SETTINGS_KEYS = %i[host_video panelists_video practice_session hd_video approval_type
registration_type audio auto_recording enforce_login
enforce_login_domains alternative_hosts close_registration
show_share_button allow_multiple_devices on_demand
request_permission_to_unmute_participants global_dial_in_countries
contact_name contact_email registrants_restrict_number
post_webinar_survey survey_url registrants_email_notification
meeting_authentication authentication_option
authentication_domains registrants_confirmation_email question_answer].freeze
def webinar_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:host_id).permit(%i[page_size page_number])
Utils.parse_response self.class.get("/users/#{params[:host_id]}/webinars", query: params.except(:host_id), headers: request_headers)
end
def webinar_create(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:host_id).permit(:topic, :type, :start_time, :duration,
:timezone, :password, :agenda,
recurrence: RECURRENCE_KEYS,
settings: SETTINGS_KEYS)
# TODO: process recurrence keys based on constants
# TODO: process settings keys based on constants
Utils.parse_response self.class.post("/users/#{params[:host_id]}/webinars", body: params.except(:host_id).to_json, headers: request_headers)
end
def webinar_get(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id)
Utils.parse_response self.class.get("/webinars/#{params[:id]}", headers: request_headers)
end
def webinar_update(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(:topic, :type, :start_time, :duration,
:timezone, :password, :agenda,
recurrence: RECURRENCE_KEYS,
settings: SETTINGS_KEYS)
Utils.parse_response self.class.patch("/webinars/#{params[:id]}", body: params.except(:id).to_json, headers: request_headers)
end
def webinar_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(:occurrence_id)
Utils.parse_response self.class.delete("/webinars/#{params[:id]}", query: params.except(:id), headers: request_headers)
end
def webinar_registrants_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(%i[occurrence_id status page_size page_number])
Utils.parse_response self.class.get("/webinars/#{params[:id]}/registrants", query: params.except(:id), headers: request_headers)
end
def webinar_registrant_add(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[id email first_name last_name])
.permit(%i[occurrence_ids address city country zip state phone
industry org job_title purchasing_time_frame role_in_purchase_process
no_of_employees comments custom_questions])
Utils.parse_response self.class.post("/webinars/#{params[:id]}/registrants", body: params.except(:id, :occurrence_ids).to_json, query: params.slice(:occurrence_ids), headers: request_headers)
end
def webinar_registrants_status_update(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[id action])
.permit(:occurrence_id, registrants: [])
Utils.parse_response self.class.put("/webinars/#{params[:id]}/registrants/status", body: params.except(:id, :occurrence_id).to_json, query: params.slice(:occurrence_id), headers: request_headers)
end
def past_webinar_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id)
Utils.parse_response self.class.get("/past_webinars/#{params[:id]}/instances", headers: request_headers)
end
def webinar_registrant_get(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[webinar_id id]).permit(:occurrence_id)
Utils.parse_response self.class.get("/webinars/#{params[:webinar_id]}/registrants/#{params[:id]}", query: params.except(:webinar_id, :id), headers: request_headers)
end
def webinar_polls_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:webinar_id)
Utils.parse_response self.class.get("/webinars/#{params[:webinar_id]}/polls", headers: request_headers)
end
def webinar_poll_get(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[webinar_id poll_id])
Utils.parse_response self.class.get("/webinars/#{params[:webinar_id]}/polls/#{params[:poll_id]}", headers: request_headers)
end
def webinar_panelist_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:webinar_id)
Utils.parse_response self.class.get("/webinars/#{params[:webinar_id]}/panelists", headers: request_headers)
end
end
end
end
|
espen/zoom_rb
|
lib/zoom/actions/recording.rb
|
<gh_stars>10-100
# frozen_string_literal: true
module Zoom
module Actions
module Recording
RECORDING_SETTINGS_KEYS = %i[share_recording recording_authentication
authentication_option authentication_domains viewer_download password
on_demand approval_type send_email_to_host show_social_share_buttons].freeze
def recording_list(*args)
options = Zoom::Params.new(Utils.extract_options!(args))
options.require(:user_id)
Utils.process_datetime_params!(%i[from to], options)
Utils.parse_response self.class.get("/users/#{options[:user_id]}/recordings", query: options.except(:user_id), headers: request_headers)
end
def meeting_recording_get(*args)
options = Zoom::Params.new(Utils.extract_options!(args))
options.require(:meeting_id)
Utils.parse_response self.class.get("/meetings/#{options[:meeting_id]}/recordings/settings", query: options.except(:meeting_id), headers: request_headers)
end
def meeting_recording_settings_get(*args)
options = Zoom::Params.new(Utils.extract_options!(args))
options.require(:meeting_id)
Utils.parse_response self.class.get("/meetings/#{options[:meeting_id]}/recordings/settings", query: options.except(:meeting_id), headers: request_headers)
end
def meeting_recording_settings_update(*args)
options = Zoom::Params.new(Utils.extract_options!(args))
options.require(:meeting_id).permit(RECORDING_SETTINGS_KEYS)
Utils.parse_response self.class.patch("/meetings/#{options[:meeting_id]}/recordings/settings", body: options.except(:meeting_id).to_json, headers: request_headers)
end
def meeting_recording_file_delete(*args)
options = Zoom::Params.new(Utils.extract_options!(args))
options.require(%i[meeting_id recording_id])
Utils.parse_response self.class.delete("/meetings/#{options[:meeting_id]}/recordings/#{options[:recording_id]}", query: options.except(:meeting_id, :recording_id), headers: request_headers)
end
end
end
end
|
espen/zoom_rb
|
lib/zoom/actions/user.rb
|
<filename>lib/zoom/actions/user.rb
# frozen_string_literal: true
module Zoom
module Actions
module User
def user_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.permit(%i[status page_size role_id page_number include_fields next_page_token])
response = self.class.get('/users', query: params, headers: request_headers)
Utils.parse_response(response)
end
def user_create(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
require_param_keys = %i[action email type]
require_param_keys.append(:password) if params[:action] == 'autoCreate'
params.require(require_param_keys)
params.permit_value(:action, Zoom::Constants::User::CREATE_TYPES.keys)
Utils.parse_response self.class.post('/users', body: { action: params[:action], user_info: params.except(:action) }.to_json, headers: request_headers)
end
def user_get(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(:login_type)
Utils.parse_response self.class.get("/users/#{params[:id]}", query: params.except(:id), headers: request_headers)
end
def user_update(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(%i[first_name last_name type pmi timezone dept vanity_name host_key cms_user_id])
Utils.parse_response self.class.patch("/users/#{params[:id]}", body: params.except(:id), headers: request_headers)
end
def user_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(%i[action transfer_email transfer_meeting transfer_webinar transfer_recording])
Utils.parse_response self.class.delete("/users/#{params[:id]}", query: params.except(:id), headers: request_headers)
end
def user_assistants_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:user_id)
Utils.parse_response(self.class.get("/users/#{params[:user_id]}/assistants", query: params.except(:user_id), headers: request_headers))
end
def user_assistants_create(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:user_id).permit(:assistants)
Utils.parse_response self.class.post("/users/#{params[:user_id]}/assistants", body: params.except(:user_id).to_json, headers: request_headers)
end
def user_assistants_delete_all(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:user_id)
Utils.parse_response(self.class.delete("/users/#{params[:user_id]}/assistants", query: params.except(:user_id), headers: request_headers))
end
def user_assistants_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[user_id assistant_id])
Utils.parse_response(self.class.delete("/users/#{params[:user_id]}/assistants/#{params[:assistant_id]}", query: params.except(:user_id, :assistant_id), headers: request_headers))
end
def user_schedulers_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:user_id)
Utils.parse_response(self.class.get("/users/#{params[:user_id]}/schedulers", query: params.except(:user_id), headers: request_headers))
end
def user_schedulers_delete_all(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:user_id)
Utils.parse_response(self.class.delete("/users/#{params[:user_id]}/schedulers", query: params.except(:user_id), headers: request_headers))
end
def user_schedulers_delete(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(%i[user_id scheduler_id])
Utils.parse_response(self.class.delete("/users/#{params[:user_id]}/schedulers/#{params[:scheduler_id]}", query: params.except(:user_id, :scheduler_id), headers: request_headers))
end
def user_settings_get(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(:login_type)
Utils.parse_response self.class.get("/users/#{params[:id]}/settings", query: params.except(:id), headers: request_headers)
end
def user_settings_update(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(%i[schedule_meeting in_meeting email_notification recording telephony feature tsp])
Utils.parse_response self.class.patch("/users/#{params[:id]}/settings", body: params.except(:id).to_json, headers: request_headers)
end
def user_email_check(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:email)
Utils.parse_response(self.class.get('/users/email', query: params.slice(:email), headers: request_headers))
end
def user_recordings_list(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(%i[page_size next_page_token mc trash from to trash_type])
Utils.parse_response self.class.get("/users/#{params[:id]}/recordings", query: params.except(:id), headers: request_headers)
end
def user_token(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:user_id).permit(%i[type ttl])
Utils.parse_response self.class.get("/users/#{params[:user_id]}/token", query: params.except(:user_id), headers: request_headers)
end
def user_permissions(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:user_id)
Utils.parse_response self.class.get("/users/#{params[:user_id]}/permissions", headers: request_headers)
end
def user_vanity_name(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:vanity_name)
Utils.parse_response self.class.get("/users/vanity_name", query: params.slice(:vanity_name), headers: request_headers)
end
def user_password_update(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:id).permit(%i[password])
Utils.parse_response self.class.patch("/users/#{params[:id]}/password", body: params.except(:id), headers: request_headers)
end
end
end
end
|
espen/zoom_rb
|
lib/zoom/actions/groups.rb
|
<gh_stars>10-100
# frozen_string_literal: true
module Zoom
module Actions
module Groups
def groups_list(*_args)
Utils.parse_response self.class.get('/groups', headers: request_headers)
end
def groups_get(*args)
params = Zoom::Params.new(Utils.extract_options!(args))
params.require(:group_id)
Utils.parse_response self.class.get("/groups/#{params[:group_id]}", headers: request_headers)
end
end
end
end
|
espen/zoom_rb
|
lib/zoom/version.rb
|
<reponame>espen/zoom_rb<gh_stars>10-100
# frozen_string_literal: true
module Zoom
VERSION = '0.11.0'
end
|
notonthehighstreet/swagger-docs
|
spec/spec_helper.rb
|
require "swagger/docs"
require "ostruct"
require "json"
require 'pathname'
DEFAULT_VER = Swagger::Docs::Generator::DEFAULT_VER
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.color = true
config.before(:each) do
Swagger::Docs::Config.base_api_controller = nil # use default object
end
end
def generate(config)
Swagger::Docs::Generator::write_docs(config)
end
def stub_string_verb_route(verb, action, controller, spec)
double("route", :verb => verb,
:defaults => {:action => action, :controller => controller},
:path => spec
)
end
def stub_route(verb, action, controller, spec)
double("route", :verb => double("verb", :source => verb),
:defaults => {:action => action, :controller => controller},
:path => double("path", :spec => spec)
)
end
def get_api_paths(apis, path)
apis.select{|api| api["path"] == path}
end
def get_api_operations(apis, path)
apis = get_api_paths(apis, path)
apis.collect{|api| api["operations"]}.flatten
end
def get_api_operation(apis, path, method)
operations = get_api_operations(apis, path)
operations.each{|operation| return operation if operation["method"] == method.to_s}
nil
end
def get_api_parameter(api, name)
api["parameters"].each{|param| return param if param["name"] == name}
nil
end
|
net-engine/mimemagic
|
test/mimemagic_test.rb
|
require 'minitest/autorun'
require 'mimemagic'
require 'stringio'
require 'forwardable'
class TestMimeMagic < Minitest::Test
# Do deep copy for constants of initial state.
INIT_EXTENSIONS = Marshal.load(Marshal.dump(MimeMagic::EXTENSIONS))
INIT_TYPES = Marshal.load(Marshal.dump(MimeMagic::TYPES))
INIT_MAGIC = Marshal.load(Marshal.dump(MimeMagic::MAGIC))
def setup
extentions = Marshal.load(Marshal.dump(INIT_EXTENSIONS))
types = Marshal.load(Marshal.dump(INIT_TYPES))
magic = Marshal.load(Marshal.dump(INIT_MAGIC))
MimeMagic.send(:remove_const, :EXTENSIONS) if MimeMagic.const_defined?(:EXTENSIONS)
MimeMagic.send(:remove_const, :TYPES) if MimeMagic.const_defined?(:TYPES)
MimeMagic.send(:remove_const, :MAGIC) if MimeMagic.const_defined?(:MAGIC)
MimeMagic.const_set('EXTENSIONS', extentions)
MimeMagic.const_set('TYPES', types)
MimeMagic.const_set('MAGIC', magic)
end
def test_have_type_mediatype_and_subtype
assert_equal 'text/html', MimeMagic.new('text/html').type
assert_equal 'text', MimeMagic.new('text/html').mediatype
assert_equal 'html', MimeMagic.new('text/html').subtype
end
def test_have_mediatype_helpers
assert MimeMagic.new('text/plain').text?
assert MimeMagic.new('text/html').text?
assert MimeMagic.new('application/xhtml+xml').text?
refute MimeMagic.new('application/octet-stream').text?
refute MimeMagic.new('image/png').text?
assert MimeMagic.new('image/png').image?
assert MimeMagic.new('video/ogg').video?
assert MimeMagic.new('audio/mpeg').audio?
end
def test_have_hierarchy
assert MimeMagic.new('text/html').child_of?('text/plain')
assert MimeMagic.new('text/x-java').child_of?('text/plain')
end
def test_have_extensions
assert_equal %w(htm html), MimeMagic.new('text/html').extensions
end
def test_have_comment
assert_equal 'HTML document', MimeMagic.new('text/html').comment
end
def test_recognize_extensions
assert_equal 'text/html', MimeMagic.by_extension('.html').to_s
assert_equal 'text/html', MimeMagic.by_extension('html').to_s
assert_equal 'text/html', MimeMagic.by_extension(:html).to_s
assert_equal 'application/x-ruby', MimeMagic.by_extension('rb').to_s
assert_nil MimeMagic.by_extension('crazy')
assert_nil MimeMagic.by_extension('')
end
def test_recognize_by_a_path
assert_equal 'text/html', MimeMagic.by_path('/adsjkfa/kajsdfkadsf/kajsdfjasdf.html').to_s
assert_equal 'text/html', MimeMagic.by_path('something.html').to_s
assert_equal 'application/x-ruby', MimeMagic.by_path('wtf.rb').to_s
assert_nil MimeMagic.by_path('where/am.html/crazy')
assert_nil MimeMagic.by_path('')
end
def test_recognize_xlsx_as_zip_without_magic
file = "test/files/application.vnd.openxmlformats-officedocument.spreadsheetml.sheet"
%w(msoffice rubyxl gdocs).each do |variant|
file = "test/files/application.vnd.openxmlformats-officedocument.spreadsheetml{#{variant}}.sheet"
assert_equal "application/zip", MimeMagic.by_magic(File.read(file)).to_s
assert_equal "application/zip", MimeMagic.by_magic(File.open(file, 'rb')).to_s
end
end
def test_recognize_by_magic
load "mimemagic/overlay.rb"
Dir['test/files/*'].each do |file|
mime = file[11..-1].sub('.', '/').sub(/\{\w+\}/, '')
assert_equal mime, MimeMagic.by_magic(File.read(file)).to_s
assert_equal mime, MimeMagic.by_magic(File.open(file, 'rb')).to_s
end
end
def test_recognize_all_by_magic
load 'mimemagic/overlay.rb'
%w(msoffice rubyxl gdocs).each do |variant|
file = "test/files/application.vnd.openxmlformats-officedocument.spreadsheetml{#{variant}}.sheet"
mimes = %w[application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/zip]
assert_equal mimes, MimeMagic.all_by_magic(File.read(file)).map(&:type)
end
end
def test_have_add
MimeMagic.add('application/mimemagic-test',
extensions: %w(ext1 ext2),
parents: 'application/xml',
comment: 'Comment')
assert_equal 'application/mimemagic-test', MimeMagic.by_extension('ext1').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_extension('ext2').to_s
assert_equal 'Comment', MimeMagic.by_extension('ext2').comment
assert_equal %w(ext1 ext2), MimeMagic.new('application/mimemagic-test').extensions
assert MimeMagic.new('application/mimemagic-test').child_of?('text/plain')
end
def test_process_magic
MimeMagic.add('application/mimemagic-test',
magic: [[0, 'MAGICTEST'], # MAGICTEST at position 0
[1, 'MAGICTEST'], # MAGICTEST at position 1
[9..12, 'MAGICTEST'], # MAGICTEST starting at position 9 to 12
[2, 'MAGICTEST', [[0, 'X'], [0, 'Y']]]]) # MAGICTEST at position 2 and (X at 0 or Y at 0)
assert_equal 'application/mimemagic-test', MimeMagic.by_magic('MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic('XMAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(' MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic('123456789MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic('123456789ABMAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic('123456789ABCMAGICTEST').to_s
assert_nil MimeMagic.by_magic('123456789ABCDMAGICTEST')
assert_equal 'application/mimemagic-test', MimeMagic.by_magic('X MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic('Y MAGICTEST').to_s
assert_nil MimeMagic.by_magic('Z MAGICTEST')
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new 'MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new 'XMAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new ' MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new '123456789MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new '123456789ABMAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new '123456789ABCMAGICTEST').to_s
assert_nil MimeMagic.by_magic(StringIO.new '123456789ABCDMAGICTEST')
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new 'X MAGICTEST').to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringIO.new 'Y MAGICTEST').to_s
assert_nil MimeMagic.by_magic(StringIO.new 'Z MAGICTEST')
end
class IOObject
def initialize
@io = StringIO.new('MAGICTEST')
end
extend Forwardable
delegate [:read, :size, :rewind, :eof?, :close, :seek] => :@io
end
class StringableObject
def to_s
'MAGICTEST'
end
end
def test_handle_different_file_objects
MimeMagic.add('application/mimemagic-test', magic: [[0, 'MAGICTEST']])
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(IOObject.new).to_s
assert_equal 'application/mimemagic-test', MimeMagic.by_magic(StringableObject.new).to_s
end
end
|
geekq/locale_selector
|
generators/gettext_hacks/templates/gettext_hacks.rb
|
module GetText
# Modification of the original gettext.
#
# By default all the translated texts from the po files are also html escaped
# so translators can not break the application by introducing less-than
# and ampersand characters or by trying to incorporate the <blink> tag ;-)
#
# It is possible though to turn this feature off for particular messages:
# if msgid starts with '#no_html_escaping#' then the translation returned as is,
# without html escaping.
def gettext(msgid)
translated = sgettext(msgid, nil)
if msgid =~ /^#no_html_escaping#/
translated
else
esc_html translated
end
end
def esc_html(txt)
txt.gsub(/\"|\>|\&|\</) {|ptrn| {'"' => '"', '>' => '>', '<' => '<', '&' => '&'}[ptrn] }
end
alias :_ :gettext
module_function :_, :esc_html
end
module ActiveRecord # :nodoc:
class Errors
# We adjust the gettext so the inclusion of the field name must be done explicitely
# with #{fn}. If it is omitted, then the field name is not included.
# Originally it was 'append_field = true' so if there was no #{fn} then
# the field name was appended at the beginning of the message - very
# questionable behaviour.
def localize_error_messages_with_better_default(append_field = false)
localize_error_messages_without_better_default(append_field)
end
alias_method_chain :localize_error_messages, :better_default
end
end
|
geekq/locale_selector
|
test/TestApp/test/integration/active_record_gathering_test.rb
|
<filename>test/TestApp/test/integration/active_record_gathering_test.rb
require 'test_helper'
require 'fileutils'
require 'locale_selector'
class ActiveRecordGatheringTest < Test::Unit::TestCase
def self.po_name()
# puts "po_name: #{File.expand_path(File.join(Dir.pwd, "po/default.pot"))}"
File.expand_path(File.join(Dir.pwd, "po/default.pot"))
end
def po_name()
ActiveRecordGatheringTest.po_name
end
def self.major_setup
# FileUtils.rm_f(po_name)
# Dir.chdir File.join(File.dirname(__FILE__), 'TestApp')
puts "pwd: #{`pwd`}"
# puts `rake gettext:updatepo lang=de`
end
def self.major_teardown
#Dir.chdir '..'
end
def assert_contains_string(search_for)
File.new(self.po_name).any? { |line| line =~ search_for }
end
def assert_po_matches(search_for)
po = IO.read(po_name())
assert po =~ search_for, "po content does not match #{search_for}"
end
def test_multiple_models_per_file
assert_po_matches(/ArticleProperty\|Key/)
end
def test_namespaced_model
assert_po_matches(/HumanResources::Employee\|Name/)
end
def test_model_with_observer
assert_po_matches(/User\|Name/)
end
def test_active_record_outside_rails
# TODO
end
# override the default suite generation to be able to use global setup
# and teardown. S. also "The Ruby Way", p. 637
def self.suite
mysuite = super
def mysuite.run(*args)
ActiveRecordGatheringTest.major_setup
super
ActiveRecordGatheringTest.major_teardown
end
mysuite
end
end
|
geekq/locale_selector
|
test/TestApp/config/initializers/include_plugin_initializer.rb
|
<filename>test/TestApp/config/initializers/include_plugin_initializer.rb
require File.join(File.dirname(__FILE__), '../../../../generators/gettext_hacks/templates/gettext_hacks.rb')
|
geekq/locale_selector
|
test/TestApp/app/models/human_resources/employee.rb
|
class HumanResources::Employee < ActiveRecord::Base
end
|
geekq/locale_selector
|
lib/locale_selector/gettext_tasks.rb
|
require File.join(File.dirname(__FILE__), '../locale_selector.rb')
require 'gettext'
require 'gettext/utils'
require 'activesupport'
require 'activerecord'
puts "Loading active_record parsing hacks in gettext_tasks.rb"
require 'gettext/rgettext'
require 'gettext/parser/active_record'
include GetText
def log(msg)
puts msg if false # set verbosity here
end
ActiveRecord::Base.instance_eval do
alias inherited_without_log inherited
@@active_record_classes_list = []
def inherited(subclass)
unless "#{subclass}" =~ /^CGI::/
log "registering an ActiveRecord model for later processing: #{subclass}"
active_record_classes_list << "#{subclass}"
end
inherited_without_log(subclass)
end
def active_record_classes_list
@@active_record_classes_list
end
def reset_active_record_classes_list
@@active_record_classes_list = []
end
end
module GetText
module ActiveRecordParser
log "overriding the original activerecord parser"
def self.singularize(s)
# there seems to be a difference between Rails 2.1.2 and 2.1.0
if defined?(ActiveSupport::Inflector)
ActiveSupport::Inflector.singularize(s)
else
Inflector.singularize(s)
end
end
def self.parse(file, targets = []) # :nodoc:
log "locale_selector specific version of activerecordparser.parse is parsing #{file}"
GetText.locale = "en"
begin
eval(open(file).read, TOPLEVEL_BINDING)
rescue
$stderr.puts _("Ignored '%{file}'. Solve dependencies first.") % {:file => file}
$stderr.puts $!
end
loaded_constants = ActiveRecord::Base.active_record_classes_list
ActiveRecord::Base.reset_active_record_classes_list
loaded_constants.each do |classname|
klass = eval(classname, TOPLEVEL_BINDING)
if klass.is_a?(Class) && klass < ActiveRecord::Base
log "processing class #{klass.name}"
unless (klass.untranslate_all? || klass.abstract_class?)
add_target(targets, file, singularize(klass.table_name.gsub(/_/, " ")))
unless klass.class_name == classname
add_target(targets, file, singularize(classname.gsub(/_/, " ").downcase))
end
begin
klass.columns.each do |column|
unless untranslate_column?(klass, column.name)
if @config[:use_classname]
msgid = classname + "|" + klass.human_attribute_name(column.name)
else
msgid = klass.human_attribute_name(column.name)
end
add_target(targets, file, msgid)
end
end
rescue
$stderr.puts _("No database is available.")
$stderr.puts $!
end
end
end
end
if RubyParser.target?(file)
targets = RubyParser.parse(file, targets)
end
targets.uniq!
targets
end
end
end
def gettext_domain
initializer_name = File.join(File.dirname(__FILE__),
'../../../../config/initializers/gettext.rb')
require initializer_name if File.exist?(initializer_name)
LocaleSelector::default_domain ||
ENV['GETTEXT_DOMAIN'] ||
puts("Please either set the LocaleSelector::default_domain in your environment.rb or ENV['GETTEXT_DOMAIN'].") && exit
end
def app_version
"#{gettext_domain} 1.0"
end
# based on GetText.update_pofiles
def update_po_single_language(textdomain, files, app_version, lang, po_root = "po", refpot = "tmp.pot")
rgettext(files, refpot)
FileUtils.mkdir_p(po_root) unless FileTest.exist? po_root
msgmerge("#{po_root}/#{textdomain}.pot", refpot, app_version)
msgmerge("#{po_root}/#{lang}/#{textdomain}.po", refpot, app_version)
File.delete(refpot)
end
namespace :gettext do
desc "Update pot/po files (text files with translations) " \
"Note: please make sure, that all the database connections used " \
"in your models work. Gettext connects to the database to extract " \
"field names to be translated. " \
"Use lang={language to process} or lang=all to process po-files for all languages."
task :updatepo => :environment do
require 'gettext/utils'
puts "Updating translation files for gettext domain #{gettext_domain}"
orig_msgmerge = ENV["MSGMERGE_PATH"] || "msgmerge"
ENV["MSGMERGE_PATH"] = "#{orig_msgmerge} --no-fuzzy-matching"
source_files = Dir.glob(["{app,lib,plugins}/**/*.{rb,erb,rjs,rhtml}", "plugins/**/**/*.{rb,erb,rjs,rhtml}"])
lang = ENV['lang']
if lang.nil?
fail "Use lang={language to process} or lang=all to process po-files for all languages."
else
# will work in gettext-1.94
# options = {:msgmerge => [:no_wrap, :no_fuzzy_matching, :sort_output]}
# options[:lang] = lang if lang != 'all'
# options[:verbose] = true
# puts options.inspect
# GetText.update_pofiles(gettext_domain, source_files, app_version, options)
if lang == 'all'
GetText.update_pofiles(gettext_domain, source_files, app_version)
else
update_po_single_language(gettext_domain, source_files, app_version, lang)
end
end
end
desc "Compile mo-(machine object) files."
task :makemo do
require 'gettext/utils'
GetText.create_mofiles(true, "po", "locale")
end
desc "Translation for additional (new) language, use lang=xx"
task :translate_to do
lang = ENV['lang']
if lang
puts <<-"# # #"
Please run:
mkdir po/#{lang}
msginit -i po/#{gettext_domain} -l #{lang} -o po/#{lang}/#{gettext_domain}.po --no-translator
svn add po/#{lang}
# # #
else
fail "Please provide the 'lang' parameter on the command line with the desired " +
"language code like lang=de"
end
end
end
|
geekq/locale_selector
|
lib/locale_selector.rb
|
<gh_stars>1-10
require 'uri'
=begin rdoc
= Usage
== Controller
In your controllers or in the application controller
require 'locale_selector'
and use ControllerClassMethods#offer_locales:
offer_locales :en_UK, :en_ZA, :de, :ru
You can use different text domains in different parts of your application,
if your application is large enough for multiple translation files.
Please provide the differing domain in the single controllers e.g.
class JobsController < ApplicationController
offer_locales :de, :ru, :domain => 'HR_terminology'
end
=== Persisting preferences
locale_selector provides helpers which you can use in connection with Rails
hooks like this:
class ApplicationController
before_filter :persist_locale_choice_cookie
after_filter :persist_locale_choice_in_db
def persist_locale_choice_cookie
compute_effective_locale do |requested_locale|
save_cookie requested_locale
end
end
def persist_locale_choice_in_db
compute_effective_locale do |requested_locale|
if current_user
current_user.update_attribute 'preferred_locale', requested_locale
current_user.reload
end
end
end
...
== Initializer
The default text domain can be set in a initializer
file config/initializers/gettext.rb
LocaleSelector::default_domain = 'myapp'
== View
In app/views/layouts/application.html.erb or in single views you
can use
<%= language_selector %>
Or write your own language selector helper. For the example
see the documentation for language_selector method for an implementation
example.
=end
module LocaleSelector
# Please set the gettext domain in a initializer,
# the file <tt>config/initializers/gettext.rb</tt> is recommended
# LocaleSelector::default_domain = 'myapp'
def self.default_domain=(d)
@@default_domain = d
end
def self.default_domain
defined?(@@default_domain) ? @@default_domain : 'default'
end
module ControllerClassMethods
# Usage:
# offer_locales :en_UK, :de, :domain => 'my_application'
# The default for the list of the locales is the list
# of subdirectories of the 'locale' folder.
# Possible options are:
# <tt>:domain</tt>::
# the gettext domain
# <tt>:lang_cookie_path</tt>::
# the path for cookie that remembers the user locale selection
def offer_locales(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
class_variable_set :@@offered_locales,
args.empty? ?
GetText::Rails::available_locales :
args.flatten.map{|l| l.to_s}.uniq
helper_method :effective_locale, :offered_locales
init_gettext options[:domain] || LocaleSelector::default_domain
class_variable_set :@@lang_cookie_path, options[:lang_cookie_path] || '/'
end
private
def global_offered_locales # :nodoc:
class_variable_get :@@offered_locales
end
def lang_cookie_path # :nodoc:
class_variable_get :@@lang_cookie_path
end
end
module ControllerInstanceMethods
# List of explicitely offered locales, as set during the
# initialization by #offer_locales
def offered_locales
self.class.send :global_offered_locales
end
# This helper saves the user locale selection in a cookie.
# You can adjust the cookie path during the initialization
# with #offer_locales, use the :lang_cookie_path option.
def save_cookie(requested_lang)
cookies[:lang] = {
:value => requested_lang,
:expires => 1.month.from_now,
:path => root_path
}
end
private
# Accepts a block. The locale, conciously chosen by user
# is passed to the block. Can be used for persisting the
# user choice in a database or/and in a cookie.
def compute_effective_locale
# Priority order:
# 1.query parameter 'lang'
# 2.cookie 'lang'
# 3.browser setting
requested_lang = params[:lang] || cookies[:lang]
if self.offered_locales.include? requested_lang
yield requested_lang if block_given?
return requested_lang
end
parse_and_match_accept_language || 'en'
end
def parse_and_match_accept_language # :nodoc:
parsed = parse_accept_language(request.headers['Accept-language'])
match_accept_language parsed, offered_locales
end
def parse_accept_language(s) # :nodoc:
return [] unless s
res = []
s.split(',').each do |entry|
code, prio = entry.split(';q=')
res << [code, prio ? prio.to_f : 1]
end
res.sort {|a,b| b[1] <=> a[1]}
end
def match_accept_language(parsed_accept_language, offered_langs) # :nodoc:
parsed_accept_language.each do |lang, prio|
return lang if offered_langs.include?(lang)
return lang[0..1] if offered_langs.include?(lang[0..1])
end
offered_langs[0]
end
alias effective_locale compute_effective_locale
public :effective_locale
end
module ViewInstanceMethods
# Simple text based UI element for locale/language selection, that
# you can put on every page by calling this method in your layout view.
# Lists the languages offered by application as clickable links.
# see also #offer_locales.
#
# You can provide a block (executed per language) if you would
# like to override the default list of text based \<a href=""\> elements.
#
# For example, you can easily implement an image based language selector
# language_selector do |lang, active|
# link_to image_tag("#{lang}#{active ? '' : '_inactive'}.png", :alt => lang),
# language_selector_href(lang, params)
# end
def language_selector(additional_params=params, &block)
content_tag :ul, :id => 'language_selector' do
offered_locales.map do |lang|
selected = lang == effective_locale
content_tag :li, :class => "#{lang} #{selected ? 'selected' : ''}" do
if block_given?
yield lang, selected
else
link_to(lang, language_selector_href(lang, additional_params))
end
end
end.join
end
end
# Can be used if you are going to implement your own language selection control.
# Generates a link, that links to the current page but with an additional
# 'lang' parameter.
#
# Note: if the user fills in e.g. form fields and clicks the language
# selection link afterwards, then the filled in data is lost.
def language_selector_href(lang, params)
path = (uri = request.request_uri) ? uri.split('?').first.to_s : ''
q = request.query_parameters.merge({'lang' => "#{lang}"}).map {
|k,v| "#{URI.escape(k.to_s)}=#{URI.escape(v.to_s)}" }.sort.join("&")
"#{path}?#{q}"
end
end
end
if defined?(ActionController)
ActionController::Base.send(:include, LocaleSelector::ControllerInstanceMethods)
ActionController::Base.extend LocaleSelector::ControllerClassMethods
end
if defined?(ActionView)
ActionView::Base.send(:include, LocaleSelector::ViewInstanceMethods)
end
module Locale # :nodoc:
# Patch for the gettext gem 1.92 and earlier.
# Now incorporated into gettext.
class Object
def self.parse(locale_name) # :nodoc:
# PATCH: the following line is new
locale_name = "en" if locale_name.nil? || locale_name.empty?
lang_charset, modifier = locale_name.split(/@/)
lang, charset = lang_charset.split(/\./)
language, country, script, variant = lang.gsub(/_/, "-").split('-')
language = language ? language.downcase : nil
language = "en" if language == "c" || language == "posix"
if country
if country =~ /\A[A-Z][a-z]+\Z/ #Latn => script
tmp = script
script = country
if tmp =~ /\A[A-Z]+\Z/ #US => country
country = tmp
else
country = nil
variant = tmp
end
else
country = country.upcase
if script !~ /\A[A-Z][a-z]+\Z/ #Latn => script
variant = script
script = nil
end
end
end
[language, country, charset, script, variant, modifier]
end
end
end
|
geekq/locale_selector
|
test/TestApp/test/unit/accept_language_parser_test.rb
|
<reponame>geekq/locale_selector
require 'test_helper'
require 'locale_selector'
class AcceptLanguageParserTest < Test::Unit::TestCase
include LocaleSelector::ControllerInstanceMethods
def test_parse
assert_equal [['de-de', 1], ['en-us', 0.8], ['en', 0.5], ['ru', 0.3]],
parse_accept_language('de-de,en-us;q=0.8,en;q=0.5,ru;q=0.3')
end
def test_sort
assert_equal [['de-de', 1], ['en-us', 0.8], ['ru', 0.7], ['en', 0.5]],
parse_accept_language('en;q=0.5,en-us;q=0.8,de-de,ru;q=0.7')
end
def test_match
assert_equal 'de',
match_accept_language(
[['de-de', 1], ['en-us', 0.8]], %w(en de ru))
end
end
|
geekq/locale_selector
|
test/TestApp/config/routes.rb
|
<reponame>geekq/locale_selector
ActionController::Routing::Routes.draw do |map|
# The priority is based upon order of creation: first created -> highest priority.
map.root :controller => "hello"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
|
geekq/locale_selector
|
locale_selector.gemspec
|
SPEC = Gem::Specification.new do |s|
s.name = 'locale_selector'
s.version = '1.93.1'
s.summary = 'Wraps and improves ruby-gettext, provides UI for locale selection, maintains user preferences.'
s.description = s.summary
s.author = '<NAME>'
s.email = '<EMAIL>'
s.homepage = 'http://github.com/geekq/locale_selector'
s.files = %w(MIT-LICENSE README.rdoc Rakefile TESTING.rdoc init.rb install.rb locale_selector.gemspec uninstall.rb) +
Dir.glob("{generators,lib,tasks,rails}/**/*")
Dir.glob("{generators,lib,tasks}/**/*")
s.require_path = "lib"
s.bindir = "bin"
s.has_rdoc = true
s.extra_rdoc_files = ['README.rdoc', 'TESTING.rdoc', 'MIT-LICENSE']
s.rdoc_options = ['--line-numbers', '--inline-source', '--promiscuous', '--main', 'README.rdoc']
s.add_dependency 'gettext', '1.93.0'
s.rubyforge_project = 'locale_selector'
end
|
geekq/locale_selector
|
test/TestApp/test/functional/inheritance_test.rb
|
<gh_stars>1-10
require File.dirname(__FILE__) + '/../test_helper'
# BTW: MyController = Class.new(ActionController::Base) {}
# does not work. Because of some Rails changes on the Class class?
class MyController < ActionController::Base
offer_locales :fi, :ru, :domain => 'default'
end
class MySpecialController < MyController
end
class InheritanceTest < Test::Unit::TestCase
def test_offer_locales
contr = MyController.new()
assert_equal ['fi', 'ru'], contr.offered_locales
assert_equal ['fi', 'ru'], MySpecialController.new.offered_locales
end
end
|
geekq/locale_selector
|
generators/gettext_hacks/gettext_hacks_generator.rb
|
class GettextHacksGenerator < Rails::Generator::Base
def initialize(*runtime_args)
super(*runtime_args)
end
def manifest
record do |m|
m.directory File.join('config/initializers')
m.template 'gettext_hacks.rb', File.join('config/initializers', "gettext_hacks.rb")
end
end
end
|
geekq/locale_selector
|
init.rb
|
<filename>init.rb
require 'locale_selector'
|
sboagibm/fluent-plugin-amqp
|
fluent-plugin-amqp.gemspec
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "fluent-plugin-amqp"
s.version = File.read("VERSION")
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["<NAME>", "<NAME>", "HiganWorks LLC", "<NAME>"]
s.description = "AMQP input/output plugin for fluentd"
s.email = "<EMAIL>"
s.extra_rdoc_files = [
"LICENSE.txt"
]
s.files = [
"lib/fluent/plugin/in_amqp.rb",
"lib/fluent/plugin/out_amqp.rb"
]
s.homepage = "http://github.com/giraffi/fluent-plugin-amqp"
s.licenses = ["Apache License, Version 2.0"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.25"
s.summary = "AMQP input/output plugin or fluentd"
s.required_ruby_version = '>= 2.1.0'
s.add_runtime_dependency(%q<fluentd>, [">= 0.14.8", "< 2"])
s.add_runtime_dependency(%q<bunny>, [">= 1.7", "< 3"])
# We can use this for simple mocking, but only works on Ruby 2+
s.add_development_dependency(%q<bunny-mock>, [">= 1.0"])
s.add_development_dependency(%q<shoulda>, [">= 3.5.0"])
s.add_development_dependency(%q<rake>)
s.add_development_dependency(%q<minitest>, ["< 5.0.0"])
s.add_development_dependency(%q<test-unit>, [">= 3.1.0"])
s.add_development_dependency(%q<simplecov>, [">= 0.10"])
end
|
sboagibm/fluent-plugin-amqp
|
test/plugin/test_out_plugin-headers.rb
|
# encoding: utf-8
require_relative '../helper'
require 'fluent/test'
require 'fluent/test/driver/output'
require 'fluent/plugin/out_amqp'
require 'bunny-mock'
class AMPQOutputTestForHeaders < Test::Unit::TestCase
attr_reader :driver
def setup
Fluent::Test.setup
BunnyMock.use_bunny_queue_pop_api = true
end
def get_plugin(configuration = CONFIG)
omit("BunnyMock is not avaliable") unless Object.const_defined?("BunnyMock")
@driver = create_driver(configuration)
plugin = @driver.instance
plugin.connection = BunnyMock.new
# Start the driver and wait while it initialises the threads etc
plugin.start
10.times { sleep 0.05 }
return plugin
end
CONFIG = %[
type amqp
format json
host amqp.example.com
port 5672
vhost /
user guest
pass guest
exchange my_exchange
exchange_type fanout
tag_key true
]
TLS_CONFIG = CONFIG + %[
tls true
tls_key "/etc/fluent/ssl/client.key.pem"
tls_cert "/etc/fluent/ssl/client.crt.pem"
tls_ca_certificates ["/etc/fluent/ssl/server.cacrt.pem", "/another/ca/cert.file"]
tls_verify_peer true
]
def create_driver(conf)
Fluent::Test::Driver::Output.new(Fluent::Plugin::AMQPOutput).configure(conf)
end
def test_header_message_helper(config, event)
plugin = get_plugin( config )
# Should have created the 'logs' queue
assert_equal true, plugin.connection.exchange_exists?('my_exchange')
# bind a testing queue to the exchange
queue = plugin.channel.queue 'my.test.queue'
queue.bind plugin.exch, routing_key: 'test'
# queue.test is now bound to the configured exchange
# v0.14 test driver does not permit to specify String object into #feed args.
es = Fluent::OneEventStream.new(Time.now.to_i, event)
# Emit an event through the plugins driver
@driver.run(default_tag: 'test') do
@driver.feed(es)
end
# Validate the message was delivered
assert_equal 1, queue.message_count
queue.pop
end
sub_test_case 'message_writing' do
sub_test_case 'routing_key' do
test 'Use hardcoded key when tag_key false' do
#Note that routing keys are igored when using fanout exchange types
# so the dl object shows 'my.test.queue' as thats what we setup in
# the helper function - but the message metadata shows the expected key
config = CONFIG + %[
tag_key false
key my.hardcoded.route
]
message = 'This is a simple string, not json'
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'my.hardcoded.route', meta[:key]
end
end
sub_test_case 'message_headers' do
test 'Default headers are set even if message isnt json' do
config = CONFIG + %[
<header>
name expect-default-header-value
source this.doesnt.exist
default expectMe
</header>
]
message = 'This is a simple string, not json'
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'expectMe', headers["expect-default-header-value"]
end
test 'Always use default when source is omitted' do
config = CONFIG + %[
<header>
name unmatched_source_return_default
default expectMe
</header>
]
message = 'This is a simple string, not json'
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'expectMe', headers["unmatched_source_return_default"]
end
test 'Dont set header if source is missing and default undefined' do
config = CONFIG + %[
<header>
name dont-set-this
source missing.from.input
</header>
]
message = {"aValue" => "Custard"}
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal nil, headers["dont-set-this"], "Did not expect to find 'dont-set-this' header"
end
test 'Headers are set when sending json object' do
config = CONFIG + %[
<header>
name unmatched_source_return_default
source this.doesnt.exist
default expectMe
</header>
<header>
name matched_key
source aValue
default Rhubarb
</header>
]
message = { "aValue" => "Custard"}
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'Custard', headers["matched_key"]
assert_equal 'expectMe', headers["unmatched_source_return_default"]
end
sub_test_case 'nested_headers' do
test 'Can get headers from nested keys by defining an array in "source"' do
config = CONFIG + %[
<header>
name nested_header_value
source [ "this", "is", "nested" ]
default spanishInquisition
</header>
]
message = { "this" => { "is" => { "nested" => "nobody" }}}
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'nobody', headers["nested_header_value"]
end
test 'Can get headers from nested keys by defining a dot separated string in "source"' do
config = CONFIG + %[
<header>
name nested_header_value
source this.is.nested
default spanishInquisition
</header>
]
message = { "this" => { "is" => { "nested" => "nobody" }}}
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'nobody', headers["nested_header_value"]
end
end # subection - nested headers
sub_test_case 'overloading' do
test 'Last Set with no default Wins' do
config = CONFIG + %[
<header>
name CorrelationID
source requestid
</header>
<header>
name CorrelationID
source request.id
</header>
]
message = {
"requestid" => "top-level",
"request" => { "id" => "nested" }
}
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'nested', headers["CorrelationID"]
end
test 'Last defined default will be used even if previous elements discovered' do
config = CONFIG + %[
<header>
name CorrelationID
source requestid
</header>
<header>
name CorrelationID
source request.id
default expectMe
</header>
]
message = { "requestid" => "top-level" }
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'expectMe', headers["CorrelationID"]
end
test 'Last discovered value is used when no defaults defined ' do
config = CONFIG + %[
<header>
name CorrelationID
source requestid
</header>
<header>
name CorrelationID
source request.id
</header>
]
message = {
"requestid" => "expectMe"
}
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'expectMe', headers["CorrelationID"]
end
test 'Failsafe default can be set' do
config = CONFIG + %[
<header>
name CorrelationID
default lastResort
</header>
<header>
name CorrelationID
source requestid
</header>
]
message = { }
dl, meta, message = test_header_message_helper(config, message)
headers = meta[:headers]
assert_not_nil headers, "Did not find any headers"
assert_equal 'lastResort', headers["CorrelationID"]
end
end # subection - nested headers
end # Subsection - message_headers
end
end
|
lengarvey/webpack-rails
|
lib/webpack/rails/environment.rb
|
<reponame>lengarvey/webpack-rails<gh_stars>10-100
module Webpack
module Rails
class Environment < Rack::File
def call(env)
`webpack --config config/webpack.development.js`
super(env)
end
end
end
end
|
lengarvey/webpack-rails
|
lib/webpack/rails.rb
|
require 'webpack/rails/version'
if defined? Rails::Railtie
require 'webpack/railtie'
end
|
lengarvey/webpack-rails
|
lib/webpack/rails/helper.rb
|
require 'action_view'
module Webpack
module Rails
module Helper
include ActionView::Helpers::AssetUrlHelper
include ActionView::Helpers::AssetTagHelper
def stylesheet_link_tag(*sources)
options = sources.extract_options!.stringify_keys
if options['debug'] != false
sources.map do |source|
super("/assets/#{source}", options)
end.flatten.uniq.join('\n').html_safe
else
super(*sources)
end
end
def javascript_include_tag(*sources)
options = sources.extract_options!.stringify_keys
if options['debug'] != false
sources.map do |source|
super("/assets/#{source}", options)
end.flatten.uniq.join('\n').html_safe
else
super(*sources)
end
end
end
end
end
|
lengarvey/webpack-rails
|
lib/webpack/railtie.rb
|
require 'rails'
require 'rails/railtie'
require 'webpack/rails/helper'
require 'webpack/rails/environment'
module Webpack
class Railtie < ::Rails::Railtie
config.after_initialize do |app|
ActiveSupport.on_load(:action_view) do
include Webpack::Rails::Helper
end
app.routes.prepend do
mount Webpack::Rails::Environment.new(File.join(app.config.root, 'tmp', 'assets')) => '/assets'
end
end
end
end
|
MediaGeniX/Eddy
|
app/controllers/hr/reports_controller.rb
|
class Hr::ReportsController < ApplicationController
before_action :authenticate_user!
def new
authorize [:hr, :report]
end
def create
authorize [:hr, :report]
params = report_params
start_date = params[:start_date] || Date.new(1900)
end_date = params[:end_date] || Date.new(2100)
respond_to do |format|
format.csv { send_data Trip.to_csv(start_date, end_date), filename: "trips-#{start_date}-#{end_date}.csv" }
end
end
private
def report_params
params.permit(:start_date, :end_date)
end
end
|
MediaGeniX/Eddy
|
app/controllers/welcome_controller.rb
|
class WelcomeController < ApplicationController
def index
season = Season.default
@yellow_jersey = Trip.where(trip_date: season.start_date..season.end_date).group(:user).order('sum_distance_in_meter DESC').sum(:distance_in_meter)
end
def letsencrypt
render text: "<KEY>"
end
end
|
MediaGeniX/Eddy
|
app/policies/user_policy.rb
|
<reponame>MediaGeniX/Eddy
class UserPolicy < ApplicationPolicy
def create?
show?
end
def recent?
show?
end
def index?
show?
end
def show?
user.id == record.id
end
def update?
show?
end
def edit?
show?
end
end
|
MediaGeniX/Eddy
|
db/migrate/20160315193922_create_trips.rb
|
class CreateTrips < ActiveRecord::Migration[4.2]
def change
create_table :trips do |t|
t.date :trip_date, null: false
t.references :route
t.references :user, null: false
t.string :alias, null: false
t.integer :distance_in_meter, null: false
t.timestamps null: false
end
end
end
|
MediaGeniX/Eddy
|
db/seeds.rb
|
<filename>db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
#
User.create!(name: "Admin", birthdate: Date.today, location: 0, sex: 0, email:'<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>', confirmed_at: DateTime.now)
Season.create!(start_date: Date.new(1900), end_date: Date.new(2200), default: true, name: 'Default all')
|
MediaGeniX/Eddy
|
app/helpers/trips_helper.rb
|
# == Schema Information
#
# Table name: trips
#
# id :integer not null, primary key
# trip_date :date not null
# route_id :integer
# user_id :integer not null
# alias :string not null
# distance_in_meter :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
module TripsHelper
end
|
MediaGeniX/Eddy
|
app/helpers/application_helper.rb
|
<gh_stars>0
module ApplicationHelper
def form_errors(object)
render partial: 'form_errors', locals: { object: object }
end
def meter_to_kilometer(meter)
meter / 1000.0
end
def pretty_number(number)
number_with_delimiter(number)
end
def pretty_date(date)
date.strftime("%d-%m-%Y")
end
end
|
MediaGeniX/Eddy
|
app/policies/hr/report_policy.rb
|
<filename>app/policies/hr/report_policy.rb
class Hr::ReportPolicy < ApplicationPolicy
def can?
user.admin
end
def new?
can?
end
def create?
can?
end
end
|
MediaGeniX/Eddy
|
app/models/season.rb
|
<reponame>MediaGeniX/Eddy<filename>app/models/season.rb
# == Schema Information
#
# Table name: seasons
#
# id :integer not null, primary key
# start_date :date
# end_date :date
# default :boolean default(FALSE), not null
# name :string not null
# created_at :datetime not null
# updated_at :datetime not null
# distance_in_meter :integer default(25000000)
#
class Season < ActiveRecord::Base
validates_uniqueness_of :default, if: :default
def self.default
self.where(default: true).first
end
def display_name
"#{name} (#{start_date} - #{end_date})"
end
end
|
MediaGeniX/Eddy
|
db/migrate/20160313193311_create_users.rb
|
<filename>db/migrate/20160313193311_create_users.rb
class CreateUsers < ActiveRecord::Migration[4.2]
def change
create_table :users do |t|
t.string :name, null: false
t.date :birthdate, null: false
t.integer :location, null: false, default: 0
t.integer :sex, null: false, default: 0
t.boolean :admin, null: false, default: false
t.timestamps null: false
end
end
end
|
MediaGeniX/Eddy
|
app/models/route.rb
|
<filename>app/models/route.rb<gh_stars>0
# == Schema Information
#
# Table name: routes
#
# id :integer not null, primary key
# user_id :integer not null
# alias :string not null
# distance_in_meter :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Route < Movement
def display_name
"#{self.alias} (#{self.distance_in_meter / 1000.0} km)"
end
end
|
MediaGeniX/Eddy
|
app/controllers/routes_controller.rb
|
# == Schema Information
#
# Table name: routes
#
# id :integer not null, primary key
# user_id :integer not null
# alias :string not null
# distance_in_meter :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class RoutesController < ApplicationController
before_action :authenticate_user!
before_action :get_user, only: [:create, :index]
before_action :get_route, only: [:show, :update, :destroy, :edit]
def index
@routes = policy_scope(@user.routes)
end
def create
@route = @user.routes.create(route_params)
authorize @route
end
def edit
end
def update
@route.update route_params
end
def destroy
@route.destroy
end
private
def route_params
params.require(:route).permit(:alias, :distance_in_kilometer)
end
def get_route
@route = Route.find(params[:id])
authorize @route
end
def get_user
@user = User.find(params[:user_id])
authorize @user, :edit?
end
end
|
MediaGeniX/Eddy
|
app/models/trip.rb
|
<gh_stars>0
# == Schema Information
#
# Table name: trips
#
# id :integer not null, primary key
# trip_date :date not null
# route_id :integer
# user_id :integer not null
# alias :string not null
# distance_in_meter :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Trip < Movement
belongs_to :user
validates :trip_date, presence: true
scope :sorted_by_date, -> { order(trip_date: :desc) }
def copy_to_next_working_day
copy_to_date(next_working_day(self.trip_date))
end
def copy_to_today
copy_to_date(Date.today)
end
def copy_to_same_day
copy_to_date(self.trip_date)
end
def self.create_from_route(user, date, route)
user.trips.create(
trip_date: date,
alias: route.alias,
distance_in_meter: route.distance_in_meter
)
end
def self.to_csv(start_date, end_date)
trips = self.where(trip_date: start_date..end_date).joins(:user).where("users.employee_number <> ''").group(:user).sum(:distance_in_meter)
trips_amount = self.where(trip_date: start_date..end_date).joins(:user).where("users.employee_number <> ''").select('DISTINCT trip_date').order('count_distinct_trip_date DESC').group(:user).count
CSV.generate(headers: true) do |csv|
csv << %w[name employer_number employee_number days_biked distance_biked compensation]
trips.each do |trip|
user = trip.first
amount_of_trips = trips_amount[user]
csv << [user.name, '4031861', user.employee_number, amount_of_trips, trip.second / 1000.0, trip.second / 1000.0 * 0.24]
end
end
end
private
def copy_to_date(date)
self.dup.tap do |new_trip|
new_trip.update(trip_date: date)
end
end
def next_working_day(date)
date + 1.working.days
end
end
|
MediaGeniX/Eddy
|
app/helpers/scoreboard_helper.rb
|
module ScoreboardHelper
def yellow_jersey_card(jersey_data, limit = nil)
if limit.nil?
data = jersey_data
else
data = jersey_data.first(limit)
end
jersey_card data: data,
title: "Yellow Jersey",
sub_title: "Most total distance",
table_header: "Distance",
color_value: "ffff00",
data_block: Proc.new {|(user, meter)| pretty_number(meter_to_kilometer(meter))},
user_block: Proc.new {|(user, meter)| user }
end
def polka_dot_jersey_card(jersey_data)
jersey_card data: jersey_data,
title: "Polka Dot Jersey",
sub_title: "Most days biked",
table_header: "Days",
color_value: "ff0000",
data_block: Proc.new {|(user, days)| pretty_number(days)},
user_block: Proc.new {|(user, days)| user }
end
def green_jersey_card(jersey_data)
jersey_card data: jersey_data,
title: "No Jersey",
sub_title: "Most distance on one day",
table_header: "Distance",
color_value: "ffffff",
data_block: Proc.new {|user| pretty_number(meter_to_kilometer(user.maximum_total_distance))},
user_block: Proc.new {|user| user }
end
def pink_jersey_card(jersey_data)
jersey_card data: jersey_data,
title: "Pink Jersey",
sub_title: "Most total distance (women)",
table_header: "Distance",
color_value: "FFC0CB",
data_block: Proc.new {|(user, meter)| pretty_number(meter_to_kilometer(meter))},
user_block: Proc.new {|(user, meter)| user }
end
def white_jersey_card(jersey_data)
jersey_card data: jersey_data,
title: "White Jersey",
sub_title: "Most total distance (< 26 year)",
table_header: "Distance",
color_value: "ffffff",
data_block: Proc.new {|(user, meter)| pretty_number(meter_to_kilometer(meter))},
user_block: Proc.new {|(user, meter)| user }
end
def grey_jersey_card(jersey_data)
jersey_card data: jersey_data,
title: "Grey Jersey",
sub_title: "Most total distance (> 50 year)",
table_header: "Distance",
color_value: "D3D3D3",
data_block: Proc.new {|(user, meter)| pretty_number(meter_to_kilometer(meter))},
user_block: Proc.new {|(user, meter)| user }
end
def jersey_card(data:, title:, sub_title:, table_header:, color_value:, data_block:, user_block:)
render partial: 'jersey_card',
locals: {data: data,
extract_block: data_block,
title: title,
sub_title: sub_title,
table_header: table_header,
color_value: color_value,
user_block: user_block,
}
end
end
|
MediaGeniX/Eddy
|
db/migrate/20180322193859_confirm_all_users.rb
|
<filename>db/migrate/20180322193859_confirm_all_users.rb
class ConfirmAllUsers < ActiveRecord::Migration[5.1]
def change
User.all.update_all confirmed_at: DateTime.now
end
end
|
MediaGeniX/Eddy
|
test/system/scoreboards_test.rb
|
<gh_stars>0
require 'application_system_test_case'
class ScoreboardsTest < ApplicationSystemTestCase
test "scoreboard" do
visit '/scoreboard'
assert_text "Scoreboard"
assert_text "User 1"
assert_text "0.001"
end
end
|
MediaGeniX/Eddy
|
app/helpers/routes_helper.rb
|
<filename>app/helpers/routes_helper.rb<gh_stars>0
# == Schema Information
#
# Table name: routes
#
# id :integer not null, primary key
# user_id :integer not null
# alias :string not null
# distance_in_meter :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
module RoutesHelper
end
|
MediaGeniX/Eddy
|
app/controllers/concerns/filtering_for_user_progress.rb
|
<gh_stars>0
module FilteringForUserProgress
extend ActiveSupport::Concern
included do
before_action :set_user
before_action :set_season
before_action :set_dates
before_action :set_current_meters
before_action :set_days_cycled
before_action :set_largest_distance_in_one_day
end
def set_user
@user = User.find(params[:id])
authorize @user
end
def set_season
@selected_season = (params[:season] && Season.find_by_name(params[:season])) \
|| Season.find_by_id([params[:season]]) \
|| Season.default
end
def set_dates
@start_date = (@selected_season.start_date if @selected_season) || Date.new(1900)
@end_date = (@selected_season.end_date if @selected_season) || Date.new(2200)
end
def set_current_meters
@current_meters = trips.sum(:distance_in_meter)
end
def set_days_cycled
@days_cycled = trips.count('DISTINCT trip_date')
end
def set_largest_distance_in_one_day
@largest_distance_in_one_day = trips.group(:trip_date).order('sum_distance_in_meter DESC').limit(1).sum(:distance_in_meter).values.first || 0
end
private
def trips
@user.trips.where(trip_date: @start_date..@end_date)
end
end
|
MediaGeniX/Eddy
|
app/helpers/hr/trips_helper.rb
|
<gh_stars>0
module Hr::TripsHelper
end
|
MediaGeniX/Eddy
|
app/policies/hr/user_policy.rb
|
class Hr::UserPolicy < ApplicationPolicy
def index?
show?
end
def show?
user.admin
end
def edit?
show?
end
def update?
show?
end
end
|
MediaGeniX/Eddy
|
test/controllers/scoreboard_controller_test.rb
|
<reponame>MediaGeniX/Eddy
require 'test_helper'
class ScoreboardControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
test "should assign yellow jersey" do
get :index
assert assigns(:yellow_jersey)
end
test "should assign polka dot jersey" do
get :index
assert assigns(:polka_dot_jersey)
end
test "should assign green jersey" do
get :index
assert assigns(:green_jersey)
end
test "should assign pink jersey" do
get :index
assert assigns(:pink_jersey)
end
test "should assign white jersey" do
get :index
assert assigns(:white_jersey)
end
test "should assign grey jersey" do
get :index
assert assigns(:grey_jersey)
end
end
|
MediaGeniX/Eddy
|
app/controllers/hr/users_controller.rb
|
<gh_stars>0
class Hr::UsersController < ApplicationController
before_action :authenticate_user!
before_action :get_user, only: [:edit, :update]
def index
@users = User.by_name
authorize [:hr, @users]
end
def edit
authorize [:hr, @user]
end
def update
@user.update user_params
authorize [:hr, @user]
end
private
def get_user
@user = User.find(params[:id])
authorize [:hr, @user]
end
def user_params
params.require(:user).permit(:name, :employee_number)
end
end
|
MediaGeniX/Eddy
|
app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
include Pundit
protect_from_forgery with: :exception
after_action :verify_authorized, except: [:index, :letsencrypt], unless: :devise_controller?
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
# If your model is called User
def after_sign_in_path_for(resource)
session["user_return_to"] || root_path
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_in)
devise_parameter_sanitizer.permit(:sign_up, keys: additional_devise_parameters)
devise_parameter_sanitizer.permit(:account_update, keys: additional_devise_parameters)
end
private
def user_not_authorized
flash[:error] = "You are not authorized to perform this action"
redirect_to request.headers["Referer"] || root_path
end
def additional_devise_parameters
[ :name, :birthdate, :location, :sex, :employee_number ]
end
end
|
MediaGeniX/Eddy
|
app/models/movement.rb
|
<reponame>MediaGeniX/Eddy
class Movement < ActiveRecord::Base
self.abstract_class = true
belongs_to :user
validates :alias, presence: true
validates :distance_in_meter, presence: true, numericality: { greater_than: 0 }
attr_accessor :distance_in_kilometer
def distance_in_kilometer
(read_attribute(:distance_in_meter) || 0) / 1000.0
end
def distance_in_kilometer=(value)
if value.is_a? String then value.sub!(',', '.') end
write_attribute(:distance_in_meter, (value.to_f * 1000).to_int)
end
end
|
MediaGeniX/Eddy
|
db/migrate/20180528125739_add_distance_to_season.rb
|
<reponame>MediaGeniX/Eddy<filename>db/migrate/20180528125739_add_distance_to_season.rb
class AddDistanceToSeason < ActiveRecord::Migration[5.2]
def change
add_column :seasons, :distance_in_meter, :integer, default: 25000000
end
end
|
MediaGeniX/Eddy
|
app/models/user.rb
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string not null
# birthdate :date not null
# location :integer default("belgium"), not null
# sex :integer default("male"), not null
# admin :boolean default(FALSE), not null
# created_at :datetime not null
# updated_at :datetime not null
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string
# last_sign_in_ip :string
# confirmation_token :string
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string
# employee_number :string
#
# Indexes
#
# index_users_on_confirmation_token (confirmation_token) UNIQUE
# index_users_on_email (email) UNIQUE
# index_users_on_reset_password_token (reset_password_token) UNIQUE
#
class User < ActiveRecord::Base
has_many :routes
has_many :trips
validates :name, presence: true, uniqueness: true
validates :birthdate, presence: true
validates :location, presence: true
validates :sex, presence: true
validates :email, presence: true, uniqueness: true
validates_format_of :email, with: /\@mediagenix\.tv\z/, message: 'Fill in your mediagenix.tv address'
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
enum location: [:belgium, :skopje, :USA, :asia]
enum sex: [:male, :female]
scope :by_name, -> { order('name') }
scope :women, -> { where('sex = ?', 1) }
end
|
MediaGeniX/Eddy
|
app/helpers/devise_helper.rb
|
<reponame>MediaGeniX/Eddy<filename>app/helpers/devise_helper.rb
module DeviseHelper
def devise_error_messages!
flash_alerts = []
error_key = 'errors.messages.not_saved'
if !flash.empty?
flash_alerts.push(flash[:error]) if flash[:error]
flash_alerts.push(flash[:alert]) if flash[:alert]
error_key = 'devise.failure.invalid'
end
return '' if resource.errors.empty? && flash_alerts.empty?
errors = resource.errors.empty? ? flash_alerts : resource.errors.full_messages
messages = errors.map { |msg| content_tag(:li, msg) }.join
sentence = I18n.t('errors.messages.not_saved',
count: resource.errors.count + flash_alerts.count,
resource: resource.class.model_name.human.downcase)
html = <<-HTML
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Error!</strong> #{sentence}
#{messages}
</div>
HTML
html.html_safe
end
end
|
MediaGeniX/Eddy
|
test/controllers/routes_controller_test.rb
|
<gh_stars>0
# == Schema Information
#
# Table name: routes
#
# id :integer not null, primary key
# user_id :integer not null
# alias :string not null
# distance_in_meter :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
require 'test_helper'
class RoutesControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
test "should redirect to sign_in path" do
get :index, params: { user_id: users(:one) }
assert_redirected_to new_user_session_path
end
test "should get index" do
sign_in users(:one)
get :index, params: { user_id: users(:one) }
assert_response :success
end
end
|
MediaGeniX/Eddy
|
app/controllers/trips_controller.rb
|
<reponame>MediaGeniX/Eddy
# == Schema Information
#
# Table name: trips
#
# id :integer not null, primary key
# trip_date :date not null
# route_id :integer
# user_id :integer not null
# alias :string not null
# distance_in_meter :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class TripsController < ApplicationController
before_action :authenticate_user!
before_action :get_user, only: [:create, :index, :create_from_route]
before_action :get_trip, except: [:index, :recent, :create, :create_from_route]
def index
@trips = @user.trips.sorted_by_date
end
def recent
@trips = Trip.sorted_by_date.paginate(page: params[:page], per_page: 15).includes(:user)
authorize current_user
end
def create
@trip = @user.trips.create(trip_params)
authorize @trip
end
def create_from_route
route = @user.routes.find route_params[:route]
date = route_params[:trip_date]
authorize route, :show?
@new_trip = Trip.create_from_route(@user, date, route)
end
def edit
end
def update
@trip.update trip_params
end
def destroy
@trip.destroy
end
def copy_to_next_working_day
@copied_trip = @trip.copy_to_next_working_day
authorize @copied_trip
end
def copy_to_today
@copied_trip = @trip.copy_to_today
authorize @copied_trip
end
def copy_to_same_day
@copied_trip = @trip.copy_to_same_day
authorize @copied_trip
end
private
def get_user
@user = User.find(params[:user_id])
authorize @user, :edit?
end
def get_trip
@trip = Trip.find(params[:id])
authorize @trip
end
def trip_params
params.require(:trip).permit(:trip_date, :alias, :distance_in_kilometer)
end
def route_params
params.require(:trip).permit(:trip_date, :route)
end
end
|
MediaGeniX/Eddy
|
config/deploy/production.rb
|
server 'eddy.toonwillems.be', user: 'deploy', roles: %w{web app db},
ssh_options: {
forward_agent: true,
auth_methods: ['publickey'],
port: 22
}
|
MediaGeniX/Eddy
|
app/controllers/concerns/filtering_for_scoreboard.rb
|
module FilteringForScoreboard
extend ActiveSupport::Concern
included do
before_action :set_season
before_action :set_dates
before_action :set_current_meters
before_action :set_jerseys
end
def set_season
@selected_season = (params[:season] && Season.find_by_name(params[:season])) \
|| Season.find_by_id([params[:season]]) \
|| Season.default
end
def set_dates
@start_date = (@selected_season.start_date if @selected_season) || Date.new(1900)
@end_date = (@selected_season.end_date if @selected_season) || Date.new(2200)
end
def set_current_meters
@current_meters = trips.sum(:distance_in_meter)
end
def set_jerseys
set_yellow_jersey
set_polka_dot_jersey
set_green_jersey
set_pink_jersey
set_white_jersey
set_grey_jersey
end
def set_yellow_jersey
@yellow_jersey = trips.group(:user).order('sum_distance_in_meter DESC').sum(:distance_in_meter)
end
def set_polka_dot_jersey
@polka_dot_jersey = trips.joins(:user).select('DISTINCT trip_date').order('count_distinct_trip_date DESC').group(:user).count
end
def set_green_jersey
@green_jersey = User.find_by_sql([
'SELECT MAX(total_distance) AS maximum_total_distance, name, id AS id
FROM (SELECT users.name, users.id, SUM(distance_in_meter) AS total_distance
FROM users
INNER JOIN trips ON trips.user_id = users.id
GROUP BY trip_date, users.name, users.id
HAVING trips.trip_date BETWEEN ? AND ?) AS useless_alias_for_postgres
GROUP BY name, id
ORDER BY maximum_total_distance DESC', @start_date, @end_date])
end
def set_pink_jersey
@pink_jersey = trips.joins(:user).merge(User.women).group(:user).order('sum_distance_in_meter DESC').sum(:distance_in_meter)
end
def set_white_jersey
@white_jersey = trips.joins(:user).where('users.birthdate >= ?', @start_date - 26.years).group(:user).order('sum_distance_in_meter DESC').sum(:distance_in_meter)
end
def set_grey_jersey
@grey_jersey = trips.joins(:user).where('users.birthdate <= ?', @end_date - 50.years).group(:user).order('sum_distance_in_meter DESC').sum(:distance_in_meter)
end
private
def trips
Trip.where(trip_date: @start_date..@end_date)
end
end
|
MediaGeniX/Eddy
|
app/helpers/hr/users_helper.rb
|
module Hr::UsersHelper
end
|
MediaGeniX/Eddy
|
config/routes.rb
|
Rails.application.routes.draw do
root 'welcome#index'
devise_for :users
get 'scoreboard', to: 'scoreboard#index'
get 'trips', to: 'trips#recent'
get '/.well-known/acme-challenge/:id' => 'welcome#letsencrypt'
resources :users do
member do
get 'progress', to: 'progress#index'
end
resources :locations
resources :trips do
collection do
post 'create_from_route'
end
member do
post 'copy_to_same_day'
post 'copy_to_next_working_day'
post 'copy_to_today'
end
end
resources :routes
end
namespace 'hr' do
resources :users, only: [:index, :edit, :update]
resources :reports, only: [:new, :create]
end
end
|
MediaGeniX/Eddy
|
app/controllers/scoreboard_controller.rb
|
class ScoreboardController < ApplicationController
include FilteringForScoreboard
def index
@seasons = Season.all
end
end
|
MediaGeniX/Eddy
|
db/migrate/20160315220019_create_routes.rb
|
class CreateRoutes < ActiveRecord::Migration[4.2]
def change
create_table :routes do |t|
t.references :user, null: false
t.string :alias, null: false
t.integer :distance_in_meter, null: false
t.timestamps null: false
end
end
end
|
jehoffmann/homebrew-cask
|
Casks/signal.rb
|
cask 'signal' do
version '1.18.1'
sha256 'e467abdb5f4b5b550778a5120ac3a540ef273967fede0628acceb5deba7cbc9f'
url "https://updates.signal.org/desktop/signal-desktop-mac-#{version}.zip"
appcast 'https://github.com/signalapp/Signal-Desktop/releases.atom'
name 'Signal'
homepage 'https://signal.org/'
auto_updates true
app 'Signal.app'
zap trash: [
'~/Library/Application Support/Signal',
'~/Library/Preferences/org.whispersystems.signal-desktop.helper.plist',
'~/Library/Preferences/org.whispersystems.signal-desktop.plist',
'~/Library/Saved Application State/org.whispersystems.signal-desktop.savedState',
]
end
|
mongodb-ansible-roles/ansible-role-saslauthd
|
molecule/default/tests/test_default.rb
|
# frozen_string_literal: true
describe command('saslauthd -v') do
# rubocop:disable LineLength
its('stderr') { should eq "saslauthd 2.1.27\nauthentication mechanisms: sasldb getpwent kerberos5 pam rimap shadow ldap\n\n" }
# rubocop:enable LineLength
end
|
STRd6/jqueryui-source
|
lib/jqueryui-source/version.rb
|
module Jqueryui
module Source
VERSION = "1.8.23"
end
end
|
STRd6/jqueryui-source
|
lib/jqueryui-source.rb
|
require "jqueryui-source/version"
# Check for Rails or Sprockets
if defined? ::Rails::Engine
require "jqueryui-source/rails"
elsif defined? ::Sprockets
require "jqueryui-source/sprockets"
end
module Jqueryui
module Source
end
end
|
STRd6/jqueryui-source
|
lib/jqueryui-source/rails.rb
|
<reponame>STRd6/jqueryui-source<filename>lib/jqueryui-source/rails.rb<gh_stars>1-10
module Jqueryui
module Source
class Rails < ::Rails::Engine
# auto wire assets
end
end
end
|
jarmo/spork
|
spec/spork/run_strategy/magazine_spec.rb
|
require 'spec_helper'
describe Spork::RunStrategy::Magazine do
before { ENV["SPORK_SLAVES_COUNT"] = nil }
after { ENV["SPORK_SLAVES_COUNT"] = nil }
it "uses 2 slaves by default" do
Spork::RunStrategy::Magazine::Slave_Id_Range.should == (1..2)
end
it "allows to override max slaves count via environment variable" do
ENV["SPORK_SLAVES_COUNT"] = "42"
Spork::RunStrategy.send :remove_const, :Magazine
load "spork/run_strategy/magazine.rb"
Spork::RunStrategy::Magazine::Slave_Id_Range.should == (1..42)
end
end
|
innerpeacez/rio
|
vagrant/lib/vagrant-host-shell/provisioner.rb
|
module VagrantPlugins::HostShell
class Provisioner < Vagrant.plugin('2', :provisioner)
# This handles outputting the communication data back to the UI
def handle_comm(type, data)
if [:stderr, :stdout].include?(type)
# Output the data with the proper color based on the stream.
color = type == :stdout ? :green : :red
# Clear out the newline since we add one
data = data.chomp
return if data.empty?
options = {}
options[:color] = color
@machine.ui.detail(data.chomp, options)
end
end
def provision
@machine.ui.detail(I18n.t("vagrant.provisioners.shell.running",
script: "host inline script"))
if Vagrant::Util::Platform.windows?
shell = "powershell"
flag = "-Command"
pathEnv = "PATH"
else
shell = "bash"
flag = "-c"
pathEnv = "VAGRANT_OLD_ENV_PATH"
end
result = Vagrant::Util::Subprocess.execute(
shell,
flag,
config.inline,
:notify => [:stdout, :stderr],
:workdir => config.cwd,
:env => {PATH: ENV[pathEnv]},
) do |type, data|
handle_comm(type, data)
end
if config.abort_on_nonzero && !result.exit_code.zero?
raise VagrantPlugins::HostShell::Errors::NonZeroStatusError.new(config.inline, result.exit_code)
end
end
end
end
|
innerpeacez/rio
|
vagrant/lib/vagrant-host-shell.rb
|
<reponame>innerpeacez/rio
# https://github.com/LLParse/vagrant-host-shell
module VagrantPlugins
module HostShell
lib_path = Pathname.new(File.expand_path("../vagrant-host-shell", __FILE__))
autoload :Errors, lib_path.join("errors")
end
end
require 'vagrant-host-shell/plugin'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.