repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
mohitsethi/chef-storm
recipes/default.rb
include_recipe "storm::dependencies" include_recipe "partial_search" # Get list of zookeeper hosts node.override['storm']['zookeeper']['hosts'] = search(:node, "chef_environment:#{node.chef_environment} AND role:#{node['storm']['storm_zookeeper_role']}", :filter_result => {'ipaddress' => ['ipaddress']}) node.override['storm']['nimbus']['host'] = search(:node, "chef_environment:#{node.chef_environment} AND role:#{node['storm']['storm_nimbus_role']}", :filter_result => {'ipaddress' => ['ipaddress']}).first if node['storm']['zookeeper']['hosts'].nil? Chef::Application.fatal!('No Zookeeper nodes found') end if node['storm']['nimbus']['host'].nil? Chef::Application.fatal!('No Nimbus node found') end storm_remote_name = "#{node['storm']['download_url']}#{node['storm']['download_dir']}" remote_file "#{Chef::Config[:file_cache_path]}/apache-storm-#{node[:storm][:version]}.tar.gz" do # source "#{node['storm']['download_url']}/apache-storm-#{node[:storm][:version]}/apache-storm-#{node[:storm][:version]}.tar.gz" source storm_remote_name action :create_if_missing end directory node['storm']['root_dir'] do user "#{node[:storm][:user]}" mode 00755 recursive true action :create not_if { ::File.directory?("#{node[:storm][:root_dir]}") } end execute "extract" do cwd node['storm']['root_dir'] command "tar -xzvf #{Chef::Config[:file_cache_path]}/apache-storm-#{node[:storm][:version]}.tar.gz" not_if { ::File.directory?("#{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}") } end directory node['storm']['data_dir'] do user "#{node[:storm][:user]}" mode 00755 recursive true action :create not_if { ::File.directory?("#{node[:storm][:data_dir]}") } end template "setup_storm_config" do path "#{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}/conf/storm.yaml" source "storm.yaml.erb" owner node[:storm][:user] group node[:storm][:group] mode 0744 end template "/tmp/setup_self_in_hosts.sh" do source "conf_self_in_hosts.sh" mode 0755 end execute "setup hosts file" do command "sh /tmp/setup_self_in_hosts.sh" end
mohitsethi/chef-storm
recipes/all_local.rb
<reponame>mohitsethi/chef-storm<filename>recipes/all_local.rb include_recipe "storm::default" bash "start_nimbus" do user node[:storm][:user] cwd "#{node[:storm][:data_dir]}" code <<-EOH #{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}/bin/storm nimbus >>nimbus.log 2>&1 & EOH end bash "start_ui" do user node[:storm][:user] cwd "#{node[:storm][:data_dir]}" code <<-EOH #{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}/bin/storm ui >>ui.log 2>&1 & EOH end bash "start_supervisor" do user node[:storm][:user] cwd "#{node[:storm][:data_dir]}" code <<-EOH #{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}/bin/storm supervisor >>supervisor.log 2>&1 & EOH end
mohitsethi/chef-storm
recipes/zookeeper.rb
package 'java-1.7.0-openjdk-devel' package 'bison' package 'flex' package 'gcc' package 'gcc-c++' package 'kernel-devel' package 'make' package 'm4' package 'patch' remote_file "#{Chef::Config[:file_cache_path]}/zookeeper-#{node[:zookeeper][:version]}.tar.gz" do source "#{node[:zookeeper][:download_url]}/zookeeper-#{node[:zookeeper][:version]}/zookeeper-#{node[:zookeeper][:version]}.tar.gz" mode 0655 end directory "#{node[:zookeeper][:root_dir]}" do user "#{node[:zookeeper][:user]}" mode 00755 recursive true end directory "#{node[:zookeeper][:data_dir]}" do user "#{node[:zookeeper][:user]}" mode 00755 recursive true end execute "install_zookeeper" do cwd "#{node[:zookeeper][:root_dir]}" command "tar -zxvf #{Chef::Config[:file_cache_path]}/zookeeper-#{node[:zookeeper][:version]}.tar.gz" not_if { ::File.exists?("#{node[:zookeeper][:root_dir]}/zookeeper-#{node[:zookeeper][:version]}") } end template "setup_zookeeper_config" do path "#{node[:zookeeper][:root_dir]}/zookeeper-#{node[:zookeeper][:version]}/conf/zoo.cfg" source "zoo.cfg.erb" owner node[:zookeeper][:user] group node[:zookeeper][:group] mode 0744 variables( :data_dir => node['zookeeper']['data_dir'], :clientPort => node['zookeeper']['clientPort'] ) action :create_if_missing end bash "start_zookeeper" do user node[:zookeeper][:user] cwd "#{node[:zookeeper][:data_dir]}" code <<-EOH #{node[:zookeeper][:root_dir]}/zookeeper-#{node[:zookeeper][:version]}/bin/zkServer.sh start >>zookeeper.log 2>&1 EOH end
mohitsethi/chef-storm
attributes/default.rb
# zookeeper attributes default['zookeeper']['version'] = '3.4.6' default['zookeeper']['download_url'] = 'http://www.poolsaboveground.com/apache/zookeeper' default['zookeeper']['user'] = 'root' default['zookeeper']['group'] = 'root' default['zookeeper']['root_dir'] = '/opt/zookeeper' default['zookeeper']['data_dir'] = '/var/zookeeper' default['zookeeper']['client_port'] = 2181 # general storm attributesdefault['storm']['version'] = "0.9.2-incubating" default['storm']['root_dir'] = "/opt/storm" default['storm']['user'] = 'root' default['storm']['data_dir'] = '/var/storm' default['storm']['log_dir'] = "/var/storm/log" default['storm']['java_lib_path'] = "/usr/local/lib:/opt/local/lib:/usr/lib" default['storm']['local_dir'] = "/mnt/storm" default['storm']['local_mode_zmq'] = "false" default['storm']['cluster_mode'] = "distributed" # zookeeper attributes for storm default['storm']['zookeeper']['hosts'] = [] default['storm']['zookeeper']['port'] = 2181 default['storm']['zookeeper']['root'] = "/storm" default['storm']['zookeeper']['session_timeout'] = 30000 default['storm']['zookeeper']['retry_times'] = 60 default['storm']['zookeeper']['retry_interval'] = 5000 # supervisor attributes default['storm']['supervisor']['workers'] = 4 default['storm']['supervisor']['childopts'] = "-Xmx1024m" default['storm']['supervisor']['worker_start_timeout'] = 120 default['storm']['supervisor']['worker_timeout_secs'] = 30 default['storm']['supervisor']['monitor_frequecy_secs'] = 3 default['storm']['supervisor']['heartbeat_frequency_secs'] = 5 default['storm']['supervisor']['enable'] = true # worker attributes default['storm']['worker']['childopts'] = "-Xmx1280m -XX:+UseConcMarkSweepGC -Dcom.sun.management.jmxremote" default['storm']['worker']['heartbeat_frequency_secs'] = 1 default['storm']['task']['heartbeat_frequency_secs'] = 3 default['storm']['task']['refresh_poll_secs'] = 10 default['storm']['zmq']['threads'] = 1 default['storm']['zmq']['longer_millis'] = 5000 # nimbus attributes default['storm']['nimbus']['host'] = "" default['storm']['nimbus']['thrift_port'] = 6627 default['storm']['nimbus']['childopts'] = "-Xmx1024m" default['storm']['nimbus']['task_timeout_secs'] = 30 default['storm']['nimbus']['supervisor_timeout_secs'] = 60 default['storm']['nimbus']['monitor_freq_secs'] = 10 default['storm']['nimbus']['cleanup_inbox_freq_secs'] = 600 default['storm']['nimbus']['inbox_jar_expiration_secs'] = 3600 default['storm']['nimbus']['task_launch_secs'] = 120 default['storm']['nimbus']['reassign'] = true default['storm']['nimbus']['file_copy_expiration_secs'] = 600 # ui attributes default['storm']['ui']['port'] = 8080 default['storm']['ui']['childopts'] = "-Xmx768m" # drpc attributes default['storm']['drpc']['port'] = 3772 default['storm']['drpc']['invocations_port'] = 3773 default['storm']['drpc']['request_timeout_secs'] = 600 # transactional attributes default['storm']['transactional']['zookeeper']['root'] = "/storm-transactional" default['storm']['transactional']['zookeeper']['port'] = 2181 # topology attributes default['storm']['topology']['debug'] = false default['storm']['topology']['optimize'] = true default['storm']['topology']['workers'] = 1 default['storm']['topology']['acker_executors'] = 1 default['storm']['topology']['acker_tasks'] = "null" default['storm']['topology']['tasks'] = "null" default['storm']['topology']['message_timeout_secs'] = 30 default['storm']['topology']['skip_missing_kryo_registrations'] = false default['storm']['topology']['max_task_parallelism'] = "null" default['storm']['topology']['max_spout_pending'] = "null" default['storm']['topology']['state_synchronization_timeout_secs'] = 60 default['storm']['topology']['stats_sample_rate'] = 0.05 default['storm']['topology']['fall_back_on_java_serialization'] = true default['storm']['topology']['worker_childopts'] = "null" default['zeromq']['required'] = false default['jzmq']['required'] = false default['zookeeper']['required'] = false default['storm']['version'] = '0.9.4' default['storm']['package'] = "apache-storm-#{node['storm']['version']}" default['storm']['download_url'] = 'http://apache.arvixe.com/storm' default['storm']['download_dir'] = "/apache-storm-#{node['storm']['version']}/apache-storm-#{node['storm']['version']}.tar.gz" # Default Environment & Roles default['storm']['storm_nimbus_role'] = '' default['storm']['storm_zookeeper_role'] = '' # Base packages default['storm']['packages'] = [ 'autoconf', 'bison', 'flex', 'gcc', 'gcc-c++', 'kernel-devel', 'make', 'm4', 'patch', 'wget', 'openssl-devel', 'curl', 'libuuid-devel', 'python-devel', 'unzip']
mohitsethi/chef-storm
recipes/supervisor.rb
include_recipe "storm::default" bash "start_supervisor" do user node[:storm][:user] cwd "#{node[:storm][:data_dir]}" code <<-EOH #{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}/bin/storm supervisor >>supervisor.log 2>&1 & EOH end
mohitsethi/chef-storm
recipes/nimbus.rb
include_recipe "storm::default" bash "start_nimbus" do user node[:storm][:user] cwd "#{node[:storm][:data_dir]}" code <<-EOH pid=$(pgrep -f backtype.storm.daemon.nimbus) if [ -z $pid ]; then #{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}/bin/storm nimbus >>nimbus.log 2>&1 & fi EOH end bash "start_ui" do user node[:storm][:user] cwd "#{node[:storm][:data_dir]}" code <<-EOH pid=$(pgrep -f backtype.storm.ui.core) if [ -z $pid ]; then #{node[:storm][:root_dir]}/apache-storm-#{node[:storm][:version]}/bin/storm ui >>ui.log 2>&1 & fi EOH end
ValentinAndreev/Relationship
lib/generators/relationship/install_generator.rb
<reponame>ValentinAndreev/Relationship require 'rails/generators' require 'rails/generators/active_record' module Relationship class InstallGenerator < Rails::Generators::Base include Rails::Generators::Migration source_root File.expand_path('../../generators/templates', __dir__) desc 'Generates migration file.' def create_migration_file migration_template 'add_relation.rb', 'db/migrate/add_relation.rb' end def migration_class_name if Rails::VERSION::MAJOR >= 5 "ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" else 'ActiveRecord::Migration' end end def self.next_migration_number(dirname) if ActiveRecord::Base.timestamped_migrations sleep 1 # make sure each time we get a different timestamp Time.new.utc.strftime('%Y%m%d%H%M%S') else format('%.3d', (current_migration_number(dirname) + 1)) end end desc 'Copy controller model and routes for relationship.' def manifest # Controller copy_file "relations_controller.rb", "app/controllers/relations_controller.rb" # Models copy_file "relation.rb", "app/models/relation.rb" # Route route "resources :relations, only: [ :create, :destroy ]" end end end
ValentinAndreev/Relationship
lib/relationship/version.rb
<gh_stars>0 module Relationship VERSION = '0.2.17' end
ValentinAndreev/Relationship
test/relationship_test.rb
require 'test_helper' class Relationship::Test < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Relationship end end
ValentinAndreev/Relationship
lib/generators/templates/add_relation.rb
<filename>lib/generators/templates/add_relation.rb class AddRelation < <%= migration_class_name %> def change create_table :relations do |t| t.integer :follower_id t.integer :followed_id t.timestamps end add_index :relations, :follower_id add_index :relations, :followed_id add_index :relations, [:follower_id, :followed_id], unique: true end end
ValentinAndreev/Relationship
lib/relationship.rb
<reponame>ValentinAndreev/Relationship module Relationship extend ActiveSupport::Concern included do has_many :active_relationships, class_name: 'Relation', foreign_key: 'follower_id', dependent: :destroy has_many :passive_relationships, class_name: 'Relation', foreign_key: 'followed_id', dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships end module ClassMethods def follow(other_user) active_relationships.create(followed_id: other_user.id) end def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end def followings?(other_user) following.include?(other_user) end end end
grepsedawk/rich
config/routes.rb
Rich::Engine.routes.draw do resources :files, :controller => "files" end
grepsedawk/rich
test/dummy/config/initializers/rich.rb
<gh_stars>100-1000 require "rich" if Object.const_defined?("Rich") Rich.setup do |config| # Customize ckeditor by adding configuration to config.editor (you can use any ckeditor config directive) # Look at the Rich source for default settings. These settings can also be overridden per editor instance. # Example: config.editor[:skin] = 'office2003' # ill advice, but you get the idea # Example: config.editor[:startupOutlineBlocks] = false config.image_styles = { :large => "500x500", :thumb => "100x100#" } # config.allowed_styles = :all # this is the default - show all styles # config.allowed_styles = [ :large, :original ] # config.allowed_styles = [ :large, :thumb ] config.default_style = :large #config.authentication_method = :authenticate_admin_user! end # activate Rich Rich.insert end
grepsedawk/rich
test/unit/helpers/rich/files_helper_test.rb
require 'test_helper' module Rich class FilesHelperTest < ActionView::TestCase end end
grepsedawk/rich
lib/rich/integrations/legacy_formtastic.rb
module Rich module Integrations module FormtasticBuilder def self.included(base) base.send(:include, InstanceMethods) end module InstanceMethods def rich_input(method, options) scope_type = object_name scope_id = object.id editor_options = Rich.options(options[:config], scope_type, scope_id) dom_id = "#{sanitized_object_name}_#{generate_association_input_name(method)}" ( text_input(method, options) << "<script>$(function(){$('##{dom_id}').ckeditor(function() { }, #{editor_options.to_json} );});</script>".html_safe ) end def rich_picker_input(method, options) scope_type = object_name scope_id = object.id editor_options = Rich.options(options[:config], scope_type, scope_id) dom_id = "#{sanitized_object_name}_#{generate_association_input_name(method)}" local_input_options = { :input_html => { :class => 'rich-picker', :style => editor_options[:style] } } ( string_input(method, local_input_options) << " <a href='#{Rich.editor[:richBrowserUrl]}' class='button'>#{I18n.t('picker_browse')}</a>".html_safe << "</br></br><img class='rich-image-preview' src='#{@object.send(method)}' style='height: 100px' />".html_safe << "<script>$(function(){$('##{dom_id}_input a').click(function(e){ e.preventDefault(); assetPicker.showFinder('##{dom_id}', #{editor_options.to_json.html_safe})})})</script>".html_safe << options.inspect ) end end end end end
grepsedawk/rich
app/helpers/rich/application_helper.rb
<filename>app/helpers/rich/application_helper.rb<gh_stars>100-1000 module Rich module ApplicationHelper end end
grepsedawk/rich
lib/rich/authorize.rb
<filename>lib/rich/authorize.rb<gh_stars>100-1000 module Rich module Authorize def authenticate_rich_user send(Rich.authentication_method) unless Rich.authentication_method == :none end end end
grepsedawk/rich
app/helpers/rich/files_helper.rb
module Rich module FilesHelper def thumb_for_file(file) if file.simplified_type == "image" file.rich_file.url(:rich_thumb) else asset_path "rich/document-thumb.png" end end end end
grepsedawk/rich
test/rich_test.rb
<reponame>grepsedawk/rich require 'test_helper' class RichTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Rich end end
TuningYourCode/puppet-blackfire
spec/classes/init_spec.rb
require 'spec_helper' describe 'blackfire' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) { facts } context 'with default parameters' do it do expect { is_expected.to compile }.to raise_error(%r{expects a value for parameter}) end end context 'with minimum parameters (server id and token)' do let(:params) do { server_id: 'foo', server_token: 'bar', } end context 'with minimum set of parameters' do it { is_expected.to compile } it { is_expected.to contain_class('blackfire') } it { is_expected.to contain_class('blackfire::repo') } it { is_expected.to contain_class('blackfire::agent') } it { is_expected.to contain_class('blackfire::php') } end context 'agent package' do it { is_expected.to contain_package('blackfire').with(ensure: 'latest') } end context 'agent configuration' do it { is_expected.to contain_ini_setting('server-id').with( path: '/etc/blackfire/agent', value: 'foo', ) } it { is_expected.to contain_ini_setting('server-token').with( path: '/etc/blackfire/agent', value: 'bar', ) } end context 'agent service' do it { is_expected.to contain_service('blackfire-agent').with(ensure: 'running') } end context 'probe package' do it { is_expected.to contain_package('blackfire-php').with(ensure: 'latest') } end context 'probe configuration' do it { is_expected.to contain_ini_setting('blackfire.server_id').with( value: 'foo', ) } it { is_expected.to contain_ini_setting('blackfire.server_token').with( value: 'bar', ) } end end end end end
deveye/eekk_view_tool
lib/eekk_view_tool.rb
<filename>lib/eekk_view_tool.rb require "eekk_view_tool/version" require "eekk_view_tool/renderer" module EekkViewTool # Your code goes here... end
noteflakes/lyp-server
ext.rb
<reponame>noteflakes/lyp-server Lyp.install_extension(__FILE__) require 'fileutils' require 'net/telnet' SERVER_CODE = <<EOF \\version "2.19.37" \\require "lys" #(lys:start-server) EOF module Lyp::Lilypond LYS_SERVER_PATH = File.join(Lyp::TMP_ROOT, "lys-server.ly") class << self alias_method :orig_parse_lilypond_arg, :parse_lilypond_arg def parse_lilypond_arg(arg, argv, argv_clean, options) case arg when '-s', '--server' options[:server] = true else orig_parse_lilypond_arg(arg, argv, argv_clean, options) end end alias_method :orig_invoke, :invoke def invoke(argv, opts = {}) if opts[:server] invoke_with_server(argv, opts) else orig_invoke(argv, opts) end end def invoke_with_server(argv, opts) session = setup_server_session cmd = "(lys:compile-file #{FileUtils.pwd.inspect} #{argv.map {|a| a.inspect}.join(" ")})" session.cmd(cmd) {|c| puts c.strip} session.close end def setup_server_session port = allocate_server_port(current_lilypond) server = start_server_session(port) msg = server.waitfor(/>/) puts msg.lines[0].chomp server end def allocate_server_port(lilypond_path) 1225 end def start_server_session(port) Net::Telnet::new("Host" => "localhost", "Port" => port) rescue Errno::ECONNREFUSED start_server(port) Net::Telnet::new("Host" => "localhost", "Port" => port) end def start_server(port) compile([LYS_SERVER_PATH], mode: :spawn, spawn_opts: { [:out, :err] => "/tmp/lilypond-server-#{port}.log", [:in] => "/dev/null" }) sleep 0.1 wait_for_server(port) end def wait_for_server(port) loop do begin session = Net::Telnet::new("Host" => "localhost", "Port" => port) session.close break rescue Errno::ECONNREFUSED sleep 0.1 end end end end end unless File.exists?(Lyp::Lilypond::LYS_SERVER_PATH) File.open(Lyp::Lilypond::LYS_SERVER_PATH, "w+") {|f| f << SERVER_CODE} end
createra-hoshino/MarqueeLabel
MarqueeLabel.podspec
<filename>MarqueeLabel.podspec Pod::Spec.new do |s| s.name = "MarqueeLabel" s.version = "3.2.0" s.summary = "A drop-in replacement for UILabel, which automatically adds a scrolling marquee effect when needed." s.homepage = "https://github.com/cbpowell/MarqueeLabel" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = "<NAME>" s.source = { :git => "https://github.com/cbpowell/MarqueeLabel.git", :tag => s.version.to_s } s.frameworks = 'UIKit', 'QuartzCore' s.requires_arc = true s.ios.deployment_target = '6.0' s.tvos.deployment_target = '9.0' s.default_subspec = 'ObjC' s.swift_version = '4.2' s.subspec 'ObjC' do |ss| ss.ios.deployment_target = '6.0' ss.tvos.deployment_target = '9.0' ss.source_files = 'Sources/**/*.{h,m}' end s.subspec 'Swift' do |ss| ss.ios.deployment_target = '8.0' ss.tvos.deployment_target = '9.0' ss.source_files = 'Sources/**/*.swift' end end
adamb/rudeq
spec/rude_q_spec.rb
require File.dirname(__FILE__) + '/spec_helper' describe RudeQ::ClassMethods do # ProcessQueue extends ClassMethods before(:each) do ProcessQueue.delete_all ProcessQueue.raise_on_processed = false create_some_noise end def create_some_noise ProcessQueue.create!(:queue_name => "doNT use this in Specs", :data => {:not => "to be messed with"}) ProcessQueue.create!(:queue_name => "abcde", :data => {:same_as => "the specs but already processed"}, :processed => true) end describe "get and set" do it "should work with strings" do ProcessQueue.set('abcde', "Something to set") ProcessQueue.get('abcde').should == "Something to set" end it "should work with symbols" do ProcessQueue.set('abcde', :a_symbol) ProcessQueue.get('abcde').should == :a_symbol end it "should work with arrays" do array = [1, :b, "C"] ProcessQueue.set('abcde', array) ProcessQueue.get('abcde').should == array end it "should work with hashes" do hash = {:symbol => "A string", "stringy" => 23, 74 => :cheese} ProcessQueue.set('abcde', hash) ProcessQueue.get('abcde').should == hash end it "should work with integers" do ProcessQueue.set('abcde', 7816327370) ProcessQueue.get('abcde').should == 7816327370 end it "unfortunately doesnt resolve booleans correctly" do ProcessQueue.set('abcde', true) ProcessQueue.get('abcde').should == 1 ProcessQueue.set('abcde', false) ProcessQueue.get('abcde').should == 0 end it "should :get in the same order they are :set" do ProcessQueue.set('abcde', :first) ProcessQueue.set('abcde', "second") ProcessQueue.get('abcde').should == :first ProcessQueue.set('abcde', 33.3333) ProcessQueue.get('abcde').should == "second" ProcessQueue.get('abcde').should == 33.3333 ProcessQueue.get('abcde').should be(nil) end it "should keep queues seperated" do ProcessQueue.set('queue_1', :data_1) ProcessQueue.set('queue_2', "DATA2") ProcessQueue.get('queue_2').should == "DATA2" ProcessQueue.get('queue_2').should be(nil) ProcessQueue.get('queue_1').should == :data_1 ProcessQueue.get('queue_1').should be(nil) end it "should call to_s on inputs" do qname = stub("fake input") qname.should_receive(:to_s).exactly(:twice).and_return("fake queue name") ProcessQueue.set(qname, ["Data"]) ProcessQueue.get(qname).should == ["Data"] end it "should work with queue name as strings or symbols" do ProcessQueue.set(:bah, "something about bah") ProcessQueue.get("bah").should == "something about bah" ProcessQueue.set("girah", {:craziness => "embodied"}) ProcessQueue.get(:girah).should == {:craziness => "embodied"} end end describe ".set" do it "should delegate to :create!" do ProcessQueue.should_receive(:create!).with(:queue_name => 'abcde', :data => :magical_planet) ProcessQueue.set('abcde', :magical_planet) end it "should return nil" do ProcessQueue.set('abcde', "something").should be(nil) end end describe ".get" do it "should revert a record if something goes wrong before it finishes" do ProcessQueue.raise_on_processed = true ProcessQueue.set('abcde', :this_will_remain_unprocessed) # confirm the object is in the db record = ProcessQueue.find(:first, :order => "id DESC") record.queue_name.should == 'abcde' record.data.should == :this_will_remain_unprocessed record.processed?.should == false record.token.should == nil lambda {ProcessQueue.get('abcde')}.should raise_error(RuntimeError) record.reload record.queue_name.should == 'abcde' record.data.should == :this_will_remain_unprocessed record.processed?.should == false record.token.should == nil end end describe "queue_options" do describe :processed do describe "set to :destroy" do before(:each) do @old_processed = ProcessQueue.queue_options[:processed] ProcessQueue.queue_options[:processed] = :destroy end after(:each) do ProcessQueue.queue_options[:processed] = @old_processed end it "should delete processed items" do count = ProcessQueue.count ProcessQueue.set(:abcde, "some value") ProcessQueue.count.should == (count + 1) ProcessQueue.get(:abcde).should == "some value" ProcessQueue.count.should == count end end describe "set to something crazy" do before(:each) do @old_processed = ProcessQueue.queue_options[:processed] ProcessQueue.queue_options[:processed] = :something_crazy end after(:each) do ProcessQueue.queue_options[:processed] = @old_processed end it "should raise an exception" do ProcessQueue.set(:abcde, "some value") lambda {ProcessQueue.get(:abcde)}.should raise_error(ArgumentError) end end end end describe ".backlog" do it "should count the unprocessed items for the provided queue_name" do ProcessQueue.backlog(:abcde).should == 0 ProcessQueue.set(:abcde, "a value") ProcessQueue.backlog(:abcde).should == 1 ProcessQueue.set(:something_else, "another value") 3.times { ProcessQueue.set(:abcde, :add_three_more)} ProcessQueue.backlog(:abcde).should == 4 ProcessQueue.get(:abcde).should == "a value" ProcessQueue.backlog(:abcde).should == 3 end end describe ".cleanup!" do it "should use :delete_all" do ProcessQueue.should_receive(:delete_all) # not :destroy_all ProcessQueue.cleanup! end it "should allow string inputs" do ProcessQueue.cleanup!("3600") end it "should allow integer inputs" do ProcessQueue.cleanup!(3600) end it "should not clear unprocessed items" do ProcessQueue.set('abcde', :giraffe) ProcessQueue.set('abcde', :monkey) ProcessQueue.count.should >= 2 ProcessQueue.cleanup! ProcessQueue.count.should >=2 ProcessQueue.get('abcde').should == :giraffe end it "should not clear old unprocessed items" do ProcessQueue.set('abcde', :giraffe) giraffe = ProcessQueue.find(:first, :conditions => {:data => :giraffe}) time_now = Time.now Time.stub!(:now).and_return(time_now + 1.year) giraffe.updated_at.should < 2.weeks.ago ProcessQueue.cleanup! giraffe.reload ProcessQueue.get('abcde').should == :giraffe end it "should not clear processed items newer than the argument" do ProcessQueue.set('abcde', :giraffe) ProcessQueue.get('abcde').should == :giraffe giraffe = ProcessQueue.find(:first, :conditions => {:data => :giraffe}) time_now = Time.now Time.stub!(:now).and_return(time_now + 1.week - 5.minutes) giraffe.updated_at.should > 1.week.ago giraffe.processed.should be(true) ProcessQueue.cleanup!(1.week) giraffe.reload end it "should not clear processed items newer than one hour, by default" do ProcessQueue.set('abcde', :giraffe) ProcessQueue.get('abcde').should == :giraffe giraffe = ProcessQueue.find(:first, :conditions => {:data => :giraffe}) time_now = Time.now Time.stub!(:now).and_return(time_now + 59.minutes) giraffe.updated_at.should > 1.hour.ago giraffe.processed.should be(true) ProcessQueue.cleanup!() giraffe.reload end it "should clear processed items older than the argument" do ProcessQueue.set('abcde', :giraffe) ProcessQueue.get('abcde').should == :giraffe giraffe = ProcessQueue.find(:first, :conditions => {:data => :giraffe}) time_now = Time.now Time.stub!(:now).and_return(time_now + 1.week + 5.minutes) giraffe.updated_at.should < 1.week.ago giraffe.processed.should be(true) ProcessQueue.cleanup!(1.week) lambda { giraffe.reload }.should raise_error(ActiveRecord::RecordNotFound) end it "should clear processed items older than one hour, by default" do ProcessQueue.set('abcde', :giraffe) ProcessQueue.get('abcde').should == :giraffe giraffe = ProcessQueue.find(:first, :conditions => {:data => :giraffe}) time_now = Time.now() Time.stub!(:now).and_return(time_now + 61.minutes) giraffe.updated_at.should < 1.hour.ago giraffe.processed.should be(true) ProcessQueue.cleanup! lambda { giraffe.reload }.should raise_error(ActiveRecord::RecordNotFound) end end end describe RudeQ::TokenLock do describe ".get_unique_token" do it "should create a unique token" do lots_of_tokens = Array.new(50) do RudeQ::TokenLock.get_unique_token end lots_of_tokens.uniq.should == lots_of_tokens end it "should create a unique token even if time stands still" do time_now = Time.now Time.should_receive(:now).at_least(50).times.and_return(time_now) lots_of_tokens = Array.new(50) do RudeQ::TokenLock.get_unique_token end lots_of_tokens.uniq.should == lots_of_tokens end end # it "should not return a processed item with the same token" do # @token = "<PASSWORD>" # # RudeQ::TokenLock.should respond_to(:get_unique_token) # ensure our stub is safe # RudeQ::TokenLock.should_receive(:get_unique_token).exactly(3).times.and_return(@token) # # @existing = ProcessQueue.create!(:queue_name => 'abcde', :data => :old_data, :token => @token, :processed => true) # # ProcessQueue.get('abcde').should be(nil) # # ProcessQueue.set('abcde', :new_data) # ProcessQueue.get('abcde').should == :new_data # ProcessQueue.get('abcde').should be(nil) # end end
adamb/rudeq
rudeq.gemspec
Gem::Specification.new do |s| s.name = "rudeq" s.version = "0.1" s.date = "2008-06-21" s.summary = "ActiveRecord-based DB-queue" s.email = "<EMAIL>" s.homepage = "http://github.com/matthewrudy/rudeq" s.description = "A simple DB queueing library built on top of ActiveRecord, and designed for use with MySQL." s.has_rdoc = true s.authors = ["<NAME>"] s.files = ["README", "Rakefile", "lib/rude_q.rb", "spec/database.yml", "spec/process_queue.rb", "spec/rude_q_spec.rb", "spec/schema.rb", "spec/spec.opts", "spec/spec_helper.rb"] s.test_files = ["spec/rude_q_spec.rb"] s.rdoc_options = ["--main", "README"] s.extra_rdoc_files = ["README"] s.add_dependency("activerecord") end
adamb/rudeq
spec/spec_helper.rb
require 'rubygems' require 'spec' require 'active_record' current_dir = File.dirname(__FILE__) require "#{current_dir}/../lib/rude_q" require "#{current_dir}/process_queue" config = YAML::load(IO.read(current_dir + '/database.yml')) ActiveRecord::Base.logger = Logger.new(current_dir + "/debug.log") ActiveRecord::Base.establish_connection(config['rude_q_test']) load(current_dir + "/schema.rb")
adamb/rudeq
lib/rude_q.rb
# RudeQ require 'digest/sha1' # simply doing; # class RudeQueue < ActiveRecord::Base # include RudeQ # end # will include RudeQ::ClassMethods # :get # :set module RudeQ def self.included(mod) # :nodoc: mod.extend(ClassMethods) mod.serialize(:data) end module ClassMethods # Cleanup old processed items # # RudeQueue.cleanup! # RudeQueue.cleanup!(1.week) def cleanup!(expiry=1.hour) self.delete_all(["processed = ? AND updated_at < ?", true, expiry.to_i.ago]) end # Add any serialize-able +data+ to the queue +queue_name+ (strings and symbols are treated the same) # # RudeQueue.set(:sausage_queue, Sausage.new(:sauce => "yummy")) # RudeQueue.set("sausage_queue", Sausage.new(:other => true)) # # >> RudeQueue.get("sausage_queue") # -> *yummy sausage* # >> RudeQueue.get(:sausage_queue) # -> *other_sausage* # >> RudeQueue.get(:sausage_queue) # -> nil def set(queue_name, data) queue_name = sanitize_queue_name(queue_name) self.create!(:queue_name => queue_name, :data => data) return nil # in line with Starling end # Grab the first item from the queue *queue_name* (strings and symbols are treated the same) # - it should always come out the same as it went in # - they should always come out in the same order they went in # - it will return a nil if there is no unprocessed entry in the queue # # >> RudeQueue.get(21) # -> {:a => "hash"} # >> RudeQueue.get(:a_symbol) # -> 255 # >> RudeQueue.get("a string") # -> nil def get(queue_name) qname = sanitize_queue_name(queue_name) fetch_with_lock(qname) do |record| if record processed!(record) return record.data else return nil # Starling waits indefinitely for a corresponding queue item end end end # A snapshot count of unprocessed items for the given +queue_name+ def backlog(queue_name) qname = sanitize_queue_name(queue_name) self.count(:conditions => {:queue_name => qname, :processed => false}) end def fetch_with_lock(qname, &block) # :nodoc: lock = case queue_options[:lock] when :pessimistic : RudeQ::PessimisticLock when :token : RudeQ::TokenLock else raise(ArgumentError, "bad queue_option for :lock - #{queue_options[:lock].inspect}") end lock.fetch_with_lock(self, qname, &block) end # class method to make it more easily stubbed def processed!(record) # :nodoc: case queue_options[:processed] when :set_flag record.update_attribute(:processed, true) when :destroy record.destroy else raise(ArgumentError, "bad queue_option for :processed - #{queue_options[:processed].inspect}") end end protected :processed! # configure your RudeQ # ==== :processed - what do we do after retrieving a queue item? # * <tt>:set_flag</tt> - set the +processed+ flag to +true+ (keep data in the db) [*default*] # * <tt>:destroy</tt> - destroy the processed item (keep our queue as lean as possible # # ==== :lock - what locking method should we use? # * <tt>:pessimistic</tt> - RudeQ::PessimisticLock [*default*] # * <tt>:token</tt> - RudeQ::TokenLock def queue_options @queue_options ||= {:processed => :set_flag, :lock => :pessimistic} end private def sanitize_queue_name(queue_name) # :nodoc: queue_name.to_s end end # uses standard ActiveRecord :lock => true # this will invoke a lock on the particular queue # eg. daemon1: RudeQueue.get(:abc) # daemon2: RudeQueue.get(:abc) - will have to wait for daemon1 to finish # daemon3: RudeQueue.get(:def) - will avoid the lock module PessimisticLock class << self def fetch_with_lock(klass, qname) # :nodoc: klass.transaction do record = klass.find(:first, :conditions => {:queue_name => qname, :processed => false}, :lock => true, :order => "id ASC", :limit => 1) return yield(record) end end end end # a crazy hack around database locking # that I thought was a good idea # turns out we can't make it use transactions properly # without creating a whole table lock # which misses the point # # also, it doesn't work on SQLite as it requires "UPDATE ... LIMIT 1 ORDER id ASC" module TokenLock class << self def fetch_with_lock(klass, qname) # :nodoc: token = get_unique_token klass.update_all(["token = ?", token], ["queue_name = ? AND processed = ? AND token IS NULL", qname, false], :limit => 1, :order => "id ASC") record = klass.find_by_queue_name_and_token_and_processed(qname, token, false) return yield(record) end def token_count! # :nodoc: @token_count ||= 0 @token_count += 1 return @token_count end def get_unique_token # :nodoc: digest = Digest::SHA1.new digest << Time.now.to_s digest << Process.pid.to_s digest << Socket.gethostname digest << self.token_count!.to_s # multiple requests from the same pid in the same second get different token return digest.hexdigest end end end end
adamb/rudeq
spec/schema.rb
ActiveRecord::Schema.define(:version => 1) do create_table :process_queues, :force => true do |t| t.string :queue_name t.text :data t.string :token, :default => nil t.boolean :processed, :default => false, :null => false t.timestamps end add_index :process_queues, :processed add_index :process_queues, [:queue_name, :processed] end
carwow/rubydoc
config/puma.rb
puts "puma.rb" root = File.dirname(__FILE__) + '/../' directory root rackup root + 'config.ru' preload_app! threads 4, 16 workers 1 before_fork do require_relative '../lib/preload' AppPreloader.preload! end
carwow/rubydoc
scripts/update_remote_gems.rb
<filename>scripts/update_remote_gems.rb #!/bin/env ruby require_relative '../lib/gem_updater' GemUpdater.update_remote_gems display: true
carwow/rubydoc
app.rb
<reponame>carwow/rubydoc<filename>app.rb # frozen_string_literal: true require File.join(File.dirname(__FILE__), 'init') require 'yard' require 'sinatra' require 'json' require 'fileutils' require 'extensions' require 'gem_updater' require 'gems_router' require 'gem_store' require 'digest/sha2' require 'rack/etag' require 'version_sorter' require 'pry' class Hash; alias blank? empty? end class NilClass; def blank?; true end end class NoCacheEmptyBody def initialize(app) @app = app end def call(env) status, headers, body = *@app.call(env) if headers.has_key?('Content-Length') && headers['Content-Length'].to_i == 0 headers['Cache-Control'] = 'max-age=0' end [status, headers, body] end end class DocServer < Sinatra::Base include YARD::Server DOC_PREFIXES = ['', '/search', '/list', '/static'] def self.adapter_options caching = %w(staging production).include?(ENV['RACK_ENV']) ? $CONFIG.caching : false { :libraries => {}, :options => {caching: false, single_library: false}, :server_options => {DocumentRoot: STATIC_PATH} } end def self.load_configuration set :environment, ($CONFIG.environment || 'production').to_sym set :name, $CONFIG.name || 'RubyDoc.info' set :url, $CONFIG.url || 'https://www.rubydoc.info' set :disallowed_projects, [] set :disallowed_gems, [] set :whitelisted_projects, [] set :whitelisted_gems, [] set :caching, false set :rubygems, "" end def self.load_gems_adapter return if $CONFIG.disable_gems opts = adapter_options opts[:libraries] = GemStore.new opts[:options][:router] = GemsRouter set :gems_adapter, $gems_adapter = RackAdapter.new(*opts.values) rescue Errno::ENOENT log.error "No remote_gems file to load remote gems from, not serving gems." end def self.post_all(*args, &block) args.each {|arg| post(arg, &block) } end use Rack::ConditionalGet use Rack::Head use NoCacheEmptyBody enable :static enable :dump_errors enable :lock enable :logging disable :raise_errors set :views, TEMPLATES_PATH set :public_folder, STATIC_PATH set :repos, REPOS_PATH set :tmp, TMP_PATH set :logdir, LOG_PATH set :static_cache_control, [:public, :max_age => 30] configure do load_configuration load_gems_adapter end helpers do include YARD::Templates::Helpers::HtmlHelper def notify_error erb(:error) end def cache(output) return output if settings.caching != true return '' if output.nil? || output.empty? path = cache_file FileUtils.mkdir_p(File.dirname(path)) File.open(path, "w") {|f| f.write(output) } output end def cache_file path = request.path.gsub(%r{^/|/$}, '') path = 'index' if path == '' File.join(settings.public_folder, path + '.html') end def next_row(prefix = 'r', base = 1) prefix + (@row = @row == base ? base + 1 : base).to_s end def translate_file_links(extra) extra.sub(%r{^/(frames/)?file:}, '/\1file/') end def shorten_commit_link(commit) commit.slice(0..5) end def try_load_cached_file cache_control :public, :must_revalidate, :max_age => 60 return if settings.caching != true path = cache_file if File.exist?(path) cache_control :public send_file(path, last_modified: File.mtime(path)) else last_modified Time.now end end def try_static_cache(prefix) return unless prefix == '/static' path = File.join(settings.public_folder, params['splat'].join('/')) if File.exist?(path) cache_control :public send_file(path, last_modified: File.mtime(path)) end end end # Filters # Check cache before { try_load_cached_file } # Always reset safe mode before { YARD::Config.options[:safe_mode] = true } # Indexes get '/' do @adapter = settings.gems_adapter @featured = settings.gems_adapter.libraries cache erb(:home) end get %r{/gems(?:/~([a-z]))?(?:/([0-9]+))?} do |letter, page| @letter = letter @adapter = settings.gems_adapter @page = (page || 1).to_i @max_pages = @letter ? @adapter.libraries.pages_of_letter(@letter) : 1 @libraries = @adapter.libraries @libraries = @libraries.each_of_letter(@letter, @page) if @letter cache erb(:gems_index) end DOC_PREFIXES.each do |prefix| get "#{prefix}/gems/:gemname/?*" do try_static_cache(prefix) @gemname = params['gemname'] return status(503) && "Cannot parse this gem" if settings.disallowed_gems.include?(@gemname) if settings.whitelisted_gems.include?(@gemname) puts "Dropping safe mode for #{@gemname}" YARD::Config.options[:safe_mode] = false end result = settings.gems_adapter.call(env) return status(404) && erb(:gems_404) if result.first == 404 result end end # Simple search interfaces get '/find/gems' do self.class.load_gems_adapter unless defined? settings.gems_adapter @search = params[:q] || '' @page = (params[:page] || 1).to_i @adapter = settings.gems_adapter @max_pages = @adapter.libraries.pages_of_find_by(@search) @libraries = @adapter.libraries.find_by(@search, @page) erb(:gems_index) end error do @page_title = "Unknown Error!" @error = "Something quite unexpected just happened. If you think something is wrong, please <a href='mailto:<EMAIL>'>email us</a> about it." notify_error end end
carwow/rubydoc
templates/default/fulldoc/html/setup.rb
<reponame>carwow/rubydoc # @fixme should be able to use Object.extend(T('layout')).menu_lists but for # some reason it causes a crash. def menu_lists [{:type => 'class', :title => 'Classes', :search_title => 'Class List'}, {:type => 'method', :title => 'Methods', :search_title => 'Method List'}, {:type => 'file', :title => 'Files', :search_title => 'File List'}] end
carwow/rubydoc
scripts/migrate_to_single_object_db.rb
#!/usr/bin/env ruby # Migrates .yardocs to --single-db require_relative '../init' include YARD [File.join(REPOS_PATH, '*', '*', '*'), File.join(REMOTE_GEMS_PATH, '*', '*', '*')].each do |dir| Dir[dir].each do |d| puts ">> Migrating .yardoc to single db for #{d}" Dir.chdir(d) Registry.load! Registry.save `touch .yardoc/complete` end end
carwow/rubydoc
config.ru
$:.unshift('.') require 'app' run DocServer
carwow/rubydoc
scripts/clean_docs.rb
require_relative '../init' MAX_DOCS_PER_PROJECT = 4 # [REMOTE_GEMS_PATH, REPOS_PATH].each do |source_dir| [REPOS_PATH].each do |source_dir| Dir.glob("#{source_dir}/*/*") do |project_dir| puts ">> Checking #{project_dir}" candidate_dirs = {} dir_count = 0 Dir.glob("#{project_dir}/*").each do |dir| dir_count += 1 if dir =~ /master$/ puts " >> Keeping master #{dir}" else candidate_dirs[dir] = File.new(dir).mtime.to_i end end candidate_dirs = candidate_dirs.sort_by { |dir, time| time }.map { |d| d[0] } keep_dir_count = (candidate_dirs.size > MAX_DOCS_PER_PROJECT) ? MAX_DOCS_PER_PROJECT : candidate_dirs.size keep_dir_count.times do keep_dir = candidate_dirs.shift puts " >> Keeping #{keep_dir}" end candidate_dirs.each do |dir, time| puts " >> Deleting #{dir}" FileUtils.rm_r(dir) end end end
carwow/rubydoc
lib/gems_router.rb
class GemsRouter < YARD::Server::Router def docs_prefix; 'gems' end def list_prefix; 'list/gems' end def search_prefix; 'search/gems' end def static_prefix; 'static/gems' end end
carwow/rubydoc
generate.rb
#!/usr/bin/env ruby require 'shellwords' if File.exist?('.yardopts') args = Shellwords.split(File.read('.yardopts').gsub(/^[ \t]*#.+/m, '')) args.each_with_index do |arg, i| next unless arg == '--plugin' next unless args[i + 1] cmd = "gem install --user-install yard-#{args[i + 1].inspect}" puts "[docparse] Installing plugin: #{cmd}" system(cmd) end end require 'yard' class YARD::CLI::Yardoc def yardopts(file = options_file) list = IO.read(file).shell_split list.map {|a| %w(-c --use-cache --db -b --query).include?(a) ? '-o' : a } rescue Errno::ENOENT [] end end YARD::CLI::Yardoc.run('-n', '-q')
carwow/rubydoc
scripts/puma.rb
#!/usr/bin/env puma root = File.dirname(__FILE__) + '/../' directory root rackup root + 'config.ru' environment 'production' bind 'tcp://0.0.0.0:8080' pidfile root + 'tmp/pids/server.pid' # daemonize unless ENV['DOCKERIZED'] # unless ENV['DOCKERIZED'] # stdout_redirect root + 'log/puma.log', root + 'log/puma.err.log', true # end threads 4, 16 workers 4 preload_app! before_fork do require_relative '../lib/preload' AppPreloader.preload! end
carwow/rubydoc
scripts/clean_index_cache.rb
<filename>scripts/clean_index_cache.rb<gh_stars>10-100 #!/usr/bin/env ruby # Removes index pages (gems, github, home) require_relative '../init' require_relative '../lib/cache' Cache.invalidate *%w(/gems/~*/ /github/* /featured /github /gems /stdlib /)
carwow/rubydoc
lib/configuration.rb
<reponame>carwow/rubydoc<filename>lib/configuration.rb class Configuration < Hash def self.load Configuration.new( YAML.load(ERB.new(File.read(CONFIG_FILE)).result) ) end def initialize(hash) update(hash) update('environment' => 'production') if environment.nil? end def method_missing(name, *args, &block) if name.to_s[-1,1] == "=" self[name.to_s[0...-1]] = args[0] else self[name.to_s] end end end
carwow/rubydoc
lib/helpers.rb
require 'open3' module Helpers module_function def sh(command, title = "", write_error = true) puts(log = "#{Time.now}: #{title}: #{command}") if write_error result, out_data, err_data = 0, "", "" Open3.popen3(command) do |_, out, err, thr| out_data, err_data, result = out.read, err.read, thr.value end else `#{command}` result = $? end puts(log = "#{Time.now}: #{title}, result=#{result.to_i}") if write_error && result != 0 data = "#{log}\n\nSTDOUT:\n#{out_data}\n\nSTDERR:\n#{err_data}\n\n" write_error_file(data) end result end end
carwow/rubydoc
scripts/importer.rb
require 'rest_client' RUBYDOC_URL = 'http://localhost:9292' if ARGV[0].nil? puts "Usage: importer <import-file>" exit 0 end import_file = ARGV[0] File.open(import_file, "r") do |file| while (line = file.gets) url = line.chomp puts ">> Importing #{url}" RestClient.post "#{RUBYDOC_URL}/checkout", { :scheme => 'git', :url => url, :commit => '' } sleep 5 end end
carwow/rubydoc
templates/default/layout/html/setup.rb
def javascripts super + %w(js/rubydoc_custom.js) end
carwow/rubydoc
scripts/setup_host_path.rb
require 'fileutils' FileUtils.mkdir_p(__dir__ + '/../data') File.open(__dir__ + '/../data/host_path', 'w') do |f| f.puts File.expand_path(__dir__ + '/..').gsub(/\A([A-Z]):/, '/\1') end
carwow/rubydoc
lib/source_cleaner.rb
<filename>lib/source_cleaner.rb class SourceCleaner attr_accessor :basepath def initialize(basepath) self.basepath = basepath end def clean(safe_mode = YARD::Config.options[:safe_mode]) if safe_mode puts "#{Time.now}: Cleaning #{basepath} (safemode=true)..." else puts "#{Time.now}: Not cleaning #{basepath} (safemode=false)" return end yardopts = File.join(basepath, '.yardopts') exclude = ['.yardoc', '.yardopts', '.git', '.document'] exclude += Dir.glob(File.join(basepath, 'README*')).map {|f| remove_basepath(f) } if File.file?(yardopts) yardoc = YARD::CLI::Yardoc.new class << yardoc def basepath=(bp) @basepath = bp end def basepath; @basepath end def add_extra_files(*files) files.map! {|f| f.include?("*") ? Dir.glob(File.join(basepath, f)) : f }.flatten! files.each do |f| filename = f.sub(/^(#{File.realpath(basepath)}|#{basepath})\//, '') options[:files] << YARD::CodeObjects::ExtraFileObject.new(filename, '') end end def support_rdoc_document_file!(file = '.document') return [] unless use_document_file File.read(File.join(basepath, file)). gsub(/^[ \t]*#.+/m, '').split(/\s+/) rescue Errno::ENOENT [] end end yardoc.basepath = basepath yardoc.options_file = yardopts if File.file?(yardopts) yardoc.parse_arguments exclude += yardoc.options[:files].map {|f| f.filename } exclude += yardoc.assets.keys end # make sure to keep relevant symlink targets link_exclude = exclude.inject(Array.new) do |lx, filespec| filespec = filespec.filename if filespec.respond_to?(:filename) Dir.glob(File.join(basepath, filespec)) do |file| if File.symlink?(file) ep = remove_basepath(File.realpath(file, basepath)) log.debug "Not deleting #{ep} (linked by #{file})" lx << ep end end lx end exclude += link_exclude # delete all source files minus excluded ones files = Dir.glob(basepath + '/**/**') + Dir.glob(basepath + '/.*') files = files.map {|f| remove_basepath(f) } files -= ['.', '..'] files = files.sort_by {|f| f.length }.reverse files.each do |file| begin fullfile = File.join(basepath, file) if exclude.any? {|ex| true if file == ex || file =~ /^#{ex}\// } log.debug "Skipping #{fullfile}" next end del = File.directory?(fullfile) ? Dir : File log.debug "Deleting #{fullfile}" del.delete(fullfile) rescue Errno::ENOTEMPTY, Errno::ENOENT, Errno::ENOTDIR end end end private def remove_basepath(p) p.sub(/^(#{File.realpath(basepath)}|#{basepath})\//, '') end end
carwow/rubydoc
scripts/clean_repos.rb
<reponame>carwow/rubydoc #!/usr/bin/env ruby # Removes cached repositories (gems, github, home) require_relative '../init' require 'source_cleaner' [File.join(REPOS_PATH, '*', '*', '*'), File.join(REMOTE_GEMS_PATH, '*', '**')].each do |dir| Dir[dir].each do |d| puts ">> Deleting source files for #{d}" SourceCleaner.new(d).clean end end
bonusly/cadooz
lib/cadooz/models/immutable/voucher_information.rb
<filename>lib/cadooz/models/immutable/voucher_information.rb class Cadooz::Immutable::VoucherInformation include Mixins attr_reader :response_state, :voucher_list def initialize(open_struct) @response_state = open_struct&.response_state @voucher_list = Array(open_struct&.voucher_list)&.each_with_object([]) { |v, arr| arr << Cadooz::Immutable::Voucher.new(v) } self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/catalog_product_variation.rb
class Cadooz::Immutable::CatalogProductVariation include Mixins attr_reader :currency, :name, :number, :value def initialize(open_struct) @currency = open_struct&.currency @name = open_struct&.name @number = open_struct&.number @value = Money.new((open_struct&.value.to_f * 100) || 0, @currency || 'USD') self.freeze end end
bonusly/cadooz
lib/cadooz/services/business_order_service.rb
<gh_stars>1-10 class Cadooz::BusinessOrderService DEFAULT_TIMEOUT = 10 def initialize(open_timeout = DEFAULT_TIMEOUT, read_timeout = DEFAULT_TIMEOUT) @client = Savon.client( wsdl: Cadooz.configuration.wsdl, basic_auth: [ Cadooz.configuration.username, Cadooz.configuration.password ], headers: { 'SOAPAction' => '' }, open_timeout: open_timeout, read_timeout: read_timeout ) @call = -> o, m { m ? @client.call(o, message: m) : @client.call(o) } end # Creates an order in the cadooz system based on the information given in Order. You should always create an order with a given customer reference number to avoid multiple orders of on order. The customer reference number should be unique over all your orders you do and you should save it on your site. # Returns: # The order result object contains informations about the created order. # ### IMPORTANT ### # The minimum set of information that is needed in the Order object is a unique customer_reference_number, a delivery_address and a product_number. ################# def create_order(order) response_class = Cadooz::Immutable::OrderStatus deserialize(@call.(__callee__, order.serialize), response_class, __callee__) end # Returns informations about an order. # Returns: # The order result object contains informations about the created order. def get_order_status(order_number) response_class = Cadooz::Immutable::OrderStatus deserialize(@call.(__callee__, {order_number: order_number}), response_class, __callee__) end # Returns informations about an order based on the customer order reference number given during createOrder(Order) in the field CustomerReferenceNumber. # Returns: # The order result object contains informations about the created order. def get_order_status_by_customer_reference_number(customer_reference_number) response_class = Cadooz::Immutable::OrderStatus deserialize(@call.(__callee__, {customer_reference_number: customer_reference_number}), response_class, __callee__) end # Returns informations about changes in one of the created order since the lastCheckTime. You should use this task to get changes in orders. Use the lastCheckTime to reduce the data size and the response time for the needed informations. For example: You have created an order on 01.01.2013. In the best situation you will get between 1-3 days later new change states because the order is delivered. If the order returns after a week, you will receive a new change state. Be aware, that you store your "lastCheckTime" on first request and use it next time. All changes since that time are returned. # Returns: # A list of of order result object containing informations about changed orders. def get_changed_orders(last_check_time) response_class = Cadooz::Immutable::OrderStatus deserialize(@call.(__callee__, {last_check_time: last_check_time}), response_class, __callee__) end # Order getOrder(java.lang.String orderNumber) # Returns all known data about an order identified by the cadooz order number. Be aware that not all information that we received (invoice informations etc) can be returned. Only the "necessary" informations like what is orders are stored on the order number. # Returns: # The order object or null if no order was found. def get_order(order_number) response_class = Cadooz::Immutable::Order deserialize(@call.(__callee__, {order_number: order_number}), response_class, __callee__) end # Returns a list of catalog's for the authenticated user. If an error occurs or the user is not allowed to query any catalog, an empty list will be returned. # Parameters: # includeExtraContent - If true, then some extra content is not included (like attributes and categories) # Returns: # A list of all available catalog id's for context-principal or an empty List. def get_available_catalogs(include_extra_content = false) response_class = Cadooz::Immutable::Catalog deserialize(@call.(__callee__, {include_extra_content: include_extra_content }), response_class, __callee__) end # Returns a List of ProductCategory models for CatalogProduct models or an empty list if an error occurs. # Returns: # A list of all categories or an empty list.z def get_available_categories response_class = Cadooz::Immutable::ProductCategory deserialize(@call.(__callee__, nil), response_class, __callee__) end # Returns a list of products that can be used within a order. This is specific for a generation profile and should not be mixed up with the merchant catalog getAvailableCatalogs(boolean). # Parameters: # generationProfile - a name of a generation profile defined by cadooz # Returns: # A list of generation profile products that can be used for an order inside createOrder(Order) def get_available_products(generation_profile = Cadooz.configuration.generation_profile) response_class = Cadooz::Immutable::GenerationProfileProduct deserialize(@call.(__callee__, {generation_profile: generation_profile }), response_class, __callee__) end # Returns a VoucherInformation Object. The status of the response can be determined using the method VoucherInformation.getResponseState(). # If one of the passed arguments is empty the status will be VoucherInformationState.INCORRECT_USAGE. # If passed name of the generation profile is unknown the status will be VoucherInformationState.UNKNOWN_GENERAION_PROFILE. # If passed order number is not existent or does not match the generation profile name or the authenticated user is not allow to query the order informations the status will be VoucherInformationState.ORDER_NOT_FOUND. # Successful queries will have the status VoucherInformationState.SUCCESS. # Parameters: # generationProfileName - The name of the generation profile used to create the order. # orderNumber - The number of the order. # Returns: # A VoucherInformation object. Never null. def get_vouchers_for_order(generation_profile_name = Cadooz.configuration.generation_profile, order_number) response_class = Cadooz::Immutable::VoucherInformation deserialize(@call.(__callee__, {generation_profile_name: generation_profile_name, order_number: order_number }), response_class, __callee__) end private def deserialize(response, response_class, operation) response_wrapper = Cadooz::Immutable::Response key = (operation.to_s + '_response').to_sym body = response.body[key][:return] if body.blank? object = OpenStruct.new else object = JSON.parse(body.to_json, object_class: OpenStruct) end response_object = nil if object.class == Array wrapper = response_wrapper.new( object.each_with_object([]) { |o, arr| arr << Object::const_get(response_class.to_s).new(o) }, response.xml ) response_object = wrapper unless nil_check(wrapper.object.first) elsif object.class == OpenStruct wrapper = response_wrapper.new( Object::const_get(response_class.to_s).new(object), response.xml ) response_object = wrapper unless nil_check(wrapper.object) else # TODO handle exception end response_object end def nil_check(object) object.instance_variables.each do |v| value = object.instance_variable_get(v) if value.class.to_s.include?('Cadooz::Immutable') nil_check(value) elsif value.class == Money return false unless value.cents == 0 else return false unless value.nil? end end true end end
bonusly/cadooz
lib/cadooz/models/immutable/greeting_card.rb
class Cadooz::Immutable::GreetingCard include Mixins attr_reader :subject, :text def initialize(open_struct) @subject = open_struct&.subject @text = open_struct&.text self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/generation_profile_product.rb
<filename>lib/cadooz/models/immutable/generation_profile_product.rb<gh_stars>1-10 class Cadooz::Immutable::GenerationProfileProduct include Mixins attr_reader :cadooz_product_number, :custom_value, :external_product_number, :value def initialize(open_struct) @cadooz_product_number = open_struct&.cadooz_product_number @custom_value = open_struct&.custom_value @external_product_number = open_struct&.external_product_number @value = open_struct&.value self.freeze end end
bonusly/cadooz
lib/cadooz/models/mutable/invoice_information.rb
class Cadooz::Mutable::InvoiceInformation include Mixins attr_accessor :debitor_number, :value def initialize(args={}) @debitor_number = args[:debitor_number] @value = args[:value] default_value_for_nil end end
bonusly/cadooz
lib/cadooz/models/immutable/catalog_product.rb
<filename>lib/cadooz/models/immutable/catalog_product.rb class Cadooz::Immutable::CatalogProduct include Mixins attr_reader :attributes, :categories, :mobile_shippable, :name, :number, :offline_shippable, :online_shippable, :type, :variations def initialize(open_struct) @attributes = Array(open_struct&.attributes)&.each_with_object([]) { |a, arr| arr << Cadooz::Immutable::Attributes.new(a) } @categories = Array(open_struct&.categories)&.each_with_object([]) { |c, arr| arr << Cadooz::Immutable::ProductCategory.new(c) } @mobile_shippable = open_struct&.mobile_shippable @name = open_struct&.name @number = open_struct&.number @offline_shippable = open_struct&.offline_shippable @online_shippable = open_struct&.online_shippable @type = open_struct&.type @variations = Array(open_struct&.variations)&.each_with_object([]) { |v, arr| arr << Cadooz::Immutable::CatalogProductVariation.new(v) } self.freeze end end
bonusly/cadooz
lib/cadooz/models/mutable/address.rb
class Cadooz::Mutable::Address include Mixins attr_accessor :city, :company, :country, :department, :email, :firstname, :lastname, :phone, :salutation, :state, :street, :street_addon, :zipcode def initialize(args={}) @company = args[:company] @country = args[:country] @department = args[:department] @email = args[:email] @firstname = args[:firstname] @lastname = args[:lastname] @phone = args[:phone] @salutation = args[:salutation] @state = args[:state] @street = args[:street] @street_addon = args[:street_addon] @zipcode = args[:zipcode] default_value_for_nil end end
bonusly/cadooz
spec/lib/cadooz/models_spec.rb
<reponame>bonusly/cadooz require 'spec_helper' RSpec::Matchers.define :mutable_block do match do |actual| actual.is_a? Proc actual.call == 'test' end def supports_block_expectations? true end end describe Cadooz do describe "immutable class attributes" do Dir.foreach('./lib/cadooz/models/immutable') do |model| next if ['.', '..'].include?(model) || model.include?('response.rb') name = 'Cadooz::Immutable::' + model.chomp('.rb').split('_').collect(&:capitalize).join immutable_class = Object::const_get(name).new(OpenStruct.new) context "set instance variables" do immutable_class.instance_variables.each do |var| specify { expect { immutable_class.instance_variable_set(var, 'test') }.to raise_error(RuntimeError) } end end context "assign instance variables" do immutable_class.instance_variables.each do |var| plain_name = var.to_s.gsub(':@', '') specify { expect { immutable_class.send(plain_name + '=', 'test') }.to raise_error(NoMethodError) } end end end end describe "mutable class attributes" do Dir.foreach('./lib/cadooz/models/mutable') do |model| next if ['.', '..'].include?(model) name = 'Cadooz::Mutable::' + model.chomp('.rb').split('_').collect(&:capitalize).join mutable_class = Object::const_get(name).new context "set instance variables" do mutable_class.instance_variables.each do |var| specify { expect { mutable_class.instance_variable_set(var, 'test') }.to mutable_block } end end context "assign instance variables" do mutable_class.instance_variables.each do |var| plain_name = var.to_s.gsub('@', '') specify { expect { mutable_class.send(plain_name + '=', 'test') }.to mutable_block } end end end end end
bonusly/cadooz
lib/cadooz/models/mutable/greeting_card.rb
<filename>lib/cadooz/models/mutable/greeting_card.rb class Cadooz::Mutable::GreetingCard include Mixins attr_accessor :subject, :text def initialize(args={}) @subject = args[:subject] @text = args[:text] default_value_for_nil end end
bonusly/cadooz
lib/cadooz/models/immutable/product_category.rb
class Cadooz::Immutable::ProductCategory include Mixins attr_reader :id, :description, :internal_name, :shop_name def initialize(open_struct) @id = open_struct&.id @description = open_struct&.description &.map_entries &.elements &.inject({}) { |hash, element| hash.merge(element.key.to_sym => element.value) } @internal_name = open_struct&.internal_name @shop_name = open_struct&.shop_name &.map_entries &.elements &.inject({}) { |hash, element| hash.merge(element.key.to_sym => element.value) } self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/invoice_information.rb
<reponame>bonusly/cadooz class Cadooz::Immutable::InvoiceInformation include Mixins attr_reader :debitor_number, :value def initialize(open_struct) @debitor_number = open_struct&.debitor_number @value = open_struct&.value self.freeze end end
bonusly/cadooz
lib/cadooz/models/mutable/order_position.rb
<gh_stars>1-10 class Cadooz::Mutable::OrderPosition include Mixins attr_accessor :amount, :attributes, :cadooz_product_number, :currency, :delivery_address, :external_reference_number, :greeting_card, :value, :voucher_address, :voucher_address_editable, :voucher_address_preset def initialize(args={}) @amount = args[:amount] @attributes = args[:attributes] @cadooz_product_number = args[:cadooz_product_number] @currency = args[:currency] @delivery_address = args[:delivery_address] @external_reference_number = args[:external_reference_number] @greeting_card = args[:greeting_card] @value = args[:value] @voucher_address = args[:voucher_address] @voucher_address_editable = args[:voucher_address_editable] @voucher_address_preset = args[:voucher_address_preset] end end
bonusly/cadooz
lib/cadooz/models/mutable/payment.rb
class Cadooz::Mutable::Payment include ::Mixins attr_accessor :attributes, :description, :paid, :type, :value, :verified def initialize(args={}) @attributes = args[:attributes] @description = args[:description] @paid = args[:paid] @type = args[:type] @value = args[:value] @verified = args[:verified] default_value_for_nil end end
bonusly/cadooz
spec/lib/cadooz/services_spec.rb
<gh_stars>1-10 require 'spec_helper' describe Cadooz::BusinessOrderService do include CadoozHelpers, Savon::SpecHelper before(:all) { savon.mock! } after(:all) { savon.unmock! } before(:each) do wsdl = File.read('./spec/support/BusinessOrderService.wsdl') stub_request(:get, /wsdl/).to_return(:status => 200, :body => wsdl) end class ::StubSocket def close; end end describe "instance methods" do let(:service) { Cadooz::BusinessOrderService.new } describe "create order" do let(:order) { create_order_param } context "succeeds" do let(:raw_response) { get_raw_response(:create_order, true) } let(:response) { get_serialized_response_object(:create_order, true) } it "should create the order" do message = order.serialize savon.expects(:create_order).with(message: message).returns(raw_response) expect(service.create_order(order).serialize[:response][:object]).to eq(response[:order_status]) end end context "fails" do let(:raw_response) { get_raw_response(:create_order, false) } let(:response) { get_serialized_response_object(:create_order, false) } it "should not create the order" do message = order.serialize savon.expects(:create_order).with(message: message).returns(raw_response) expect(service.create_order(order).serialize[:response][:object]).to eq(response[:order_status]) end end context "invalid" do it "should raise an exception" do message = { garbage: 'trash' } expect { service.create_order(message).serialize }.to raise_error(NoMethodError) end end end describe "get order status" do # Endpoint always returns same 'DELIVERED' response in sandbox as long as # expected parameters are passed. Thus, 'fails' context is skipped let(:raw_response) { get_raw_response(:get_order_status, true) } let(:response) { get_serialized_response_object(:get_order_status, true) } context "succeeds" do it "should get the order status" do message = { order_number: 20000 } savon.expects(:get_order_status).with(message: message).returns(raw_response) expect(service.get_order_status(20000).serialize[:response][:object]).to eq(response[:order_status]) end end context "invalid" do it "should raise an exception" do message = { garbage: 'trash' } savon.expects(:get_order_status).with(message: message).returns(raw_response) expect { service.get_order_status(message).serialize }.to raise_error(Savon::ExpectationError) end end end describe "get order status by customer reference number" do # Endpoint always returns same 'DELIVERED' response in sandbox as long as # expected parameters are passed. Thus, 'fails' context is skipped let(:raw_response) { get_raw_response(:get_order_status_by_customer_reference_number, true) } let(:response) { get_serialized_response_object(:get_order_status_by_customer_reference_number, true) } context "succeeds" do it "should get the order status" do message = { customer_reference_number: 20000 } savon.expects(:get_order_status_by_customer_reference_number).with(message: message).returns(raw_response) expect(service.get_order_status_by_customer_reference_number(20000).serialize[:response][:object]).to eq(response[:order_status]) end end context "invalid" do it "should raise an exception" do message = { garbage: 'trash' } savon.expects(:get_order_status_by_customer_reference_number).with(message: message).returns(raw_response) expect { service.get_order_status_by_customer_reference_number(message).serialize }.to raise_error(Savon::ExpectationError) end end end describe "get changed orders" do context "succeeds" do let(:raw_response) { get_raw_response(:get_changed_orders, true) } let(:response) { get_serialized_response_object(:get_changed_orders, true) } it "should get changed orders" do # Past time message = { last_check_time: Date.parse('20-02-2016') } savon.expects(:get_changed_orders).with(message: message).returns(raw_response) expect(service.get_changed_orders(Date.parse('20-02-2016')).serialize[:response][:object]).to eq(response.map { |r| r[:order_status] }) end end context "fails" do let(:raw_response) { get_raw_response(:get_changed_orders, false) } let(:response) { get_serialized_response_object(:get_changed_orders, false) } it "should return an empty response" do # Future time message = { last_check_time: Date.parse('01-03-2016') } savon.expects(:get_changed_orders).with(message: message).returns(raw_response) expect(service.get_changed_orders(Date.parse('01-03-2016'))).to eq(nil) end end context "invalid" do it "should raise an exception" do # Revisit with VCR recording of failed request end end end describe "get order" do context "succeeds" do let(:raw_response) { get_raw_response(:get_order, true) } let (:response) { get_serialized_response_object(:get_order, true) } it "should get the order" do message = { order_number: '160223-066085' } savon.expects(:get_order).with(message: message).returns(raw_response) expect(service.get_order('160223-066085').serialize[:response][:object]).to eq(response[:order]) end end context "fails" do let(:raw_response) { get_raw_response(:get_order, false) } let (:response) { get_serialized_response_object(:get_order, false) } it "should return an empty response" do message = { order_number: '9' } savon.expects(:get_order).with(message: message).returns(raw_response) expect(service.get_order('9').serialize[:response][:object]).to eq({}) end end end describe "get available catalogs" do context "succeeds" do let(:raw_response) { get_raw_response(:get_available_catalogs, true) } let(:response) { get_serialized_response_object(:get_available_catalogs, true) } it "should get the available catalogs" do message = { include_extra_content: false } savon.expects(:get_available_catalogs).with(message: message).returns(raw_response) expect(service.get_available_catalogs.serialize[:response][:object]).to eq(response[:catalog]) end end context "invalid" do it "should raise an exception" do # Revisit with VCR recording of failed request end end end describe "get available categories" do context "succeeds" do let(:raw_response) { get_raw_response(:get_available_categories, true) } let(:response) { get_serialized_response_object(:get_available_categories, true) } it "should get available categories" do savon.expects(:get_available_categories).returns(raw_response) expect(service.get_available_categories.serialize[:response][:object]).to eq(response.map { |r| r[:product_category] }) end end context "invalid" do it "should raise an exception" do # Revisit with VCR recording of failed request end end end describe "get available products" do context "succeeds" do let(:raw_response) { get_raw_response(:get_available_products, true) } let(:response) { get_serialized_response_object(:get_available_products, true) } it "should get available products" do message = { generation_profile: nil } savon.expects(:get_available_products).with(message: message).returns(raw_response) expect(service.get_available_products.serialize[:response][:object]).to eq(response.map { |r| r[:generation_profile_product] }) end end context "invalid" do it "should raise an exception" do # Revisit with VCR recording of failed request end end end describe "get vouchers for order" do context "succeeds" do let(:raw_response) { get_raw_response(:get_vouchers_for_order, true) } let(:response) { get_serialized_response_object(:get_vouchers_for_order, true) } it "should get vouchers for an order number" do message = { generation_profile_name: nil, order_number: '160223-066085' } savon.expects(:get_vouchers_for_order).with(message: message).returns(raw_response) expect(service.get_vouchers_for_order('160223-066085').serialize[:response][:object]).to eq({ response_state: 'SUCCESS' }) end end context "invalid" do # Revisit with VCR recording of failed request end end end end
bonusly/cadooz
cadooz.gemspec
<reponame>bonusly/cadooz $:.push File.expand_path('../lib', __FILE__) require 'cadooz/version' Gem::Specification.new do |s| s.name = 'cadooz' s.version = Cadooz::VERSION s.authors = ['<NAME>'] s.email = ['<EMAIL>'] s.homepage = 'http://bonus.ly' s.license = 'MIT' s.summary = 'Ruby Wrapper for cadooz SOAP API' s.description = 'cadooz is a world leader in incentive marketing and distribution of digital rewards, including gift cards, e-vouchers, etc. This gem wraps cadooz\'s BusinessOrderService SOAP API (http://business.cadooz.com/api/businessorder/v1.5.2/com/cadooz/webservice/businessorder/v152/package-summary.html)' s.files = Dir['{app,config,db,lib}/**/*'] + ['LICENSE', 'Rakefile', 'README.md'] s.add_dependency 'savon', '~> 2.12.0' s.add_dependency 'money' s.add_development_dependency 'rspec', '~> 3.4.0' s.add_development_dependency 'webmock', '~> 1.24.0' end
bonusly/cadooz
lib/cadooz/models/immutable/payment.rb
class Cadooz::Immutable::Payment include Mixins attr_reader :attributes, :description, :paid, :type, :value, :verified def initialize(open_struct) @attributes = open_struct&.attributes &.map_entries &.elements &.inject({}) { |hash, element| hash.merge(element.key.to_sym => element.value) } @description = open_struct&.description @paid = open_struct&.paid @type = open_struct&.type @value = open_struct&.value @verified = open_struct&.verified self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/address.rb
<reponame>bonusly/cadooz class Cadooz::Immutable::Address include Mixins attr_reader :city, :company, :country, :department, :email, :firstname, :lastname, :phone, :salutation, :state, :street, :street_addon, :zip_code def initialize(open_struct) @city = open_struct&.city @company =open_struct&.company @country = open_struct&.country @department = open_struct&.department @email = open_struct&.email @firstname = open_struct&.firstname @lastname = open_struct&.lastname @phone = open_struct&.phone @salutation = open_struct&.salutation @state = open_struct&.state @street = open_struct&.street @street_addon = open_struct&.street_addon @zip_code = open_struct&.zipcode self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/order.rb
<reponame>bonusly/cadooz class Cadooz::Immutable::Order include Mixins attr_reader :client, :commission, :cost_owner, :cost_unit, :credit_or_number, :customer_reference_number, :delivery_address, :generation_profile, :greeting_card, :invoice_address, :invoice_information, :language, :order_attributes, :order_description, :order_positions, :payment_informations, :queue, :send_mail, :test, :website def initialize(open_struct) @client = open_struct&.client @commission = open_struct&.commission @cost_owner = open_struct&.cost_owner @cost_unit = open_struct&.cost_unit @credit_or_number = open_struct&.credit_or_number @customer_reference_number = open_struct&.customer_reference_number @delivery_address = Cadooz::Immutable::Address.new(open_struct&.delivery_address) @generation_profile = open_struct&.generation_profile @greeting_card = Cadooz::Immutable::GreetingCard.new(open_struct&.greeting_card) @invoice_address = Cadooz::Immutable::Address.new(open_struct&.invoice_address) @invoice_information = Array(open_struct&.invoice_information)&.each_with_object([]) { |i, arr| arr << Cadooz::Immutable::InvoiceInformation.new(i) } @language = open_struct&.language @order_attributes = open_struct&.order_attributes&.inject({}) { |hash, element| hash.merge(element.key.to_sym => element.value) } @order_description = open_struct&.order_description @order_positions = Array(open_struct&.order_positions)&.each_with_object([]) { |o, arr| arr << Cadooz::Immutable::OrderPosition.new(o) } @payment_informations = open_struct&.payment_informations @queue = open_struct&.queue @send_mail = open_struct&.send_mail @test = open_struct&.test @website = open_struct&.website self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/voucher.rb
<filename>lib/cadooz/models/immutable/voucher.rb class Cadooz::Immutable::Voucher include Mixins attr_reader :address, :code, :ecard_link, :evoucher_link, :pin, :product_name, :product_number, :product_variation_number, :serial_number, :value def initialize(open_struct) @address = Cadooz::Immutable::Address.new(open_struct&.address) @code = open_struct&.code @currency = open_struct&.currency @ecard_link = open_struct&.ecard_link @evoucher_link = open_struct&.evoucher_link @pin = open_struct&.pin @product_name = open_struct&.product_name @product_number = open_struct&.product_number @product_variation_number = open_struct&.product_variation_number @serial_number = open_struct&.serial_number @value = open_struct&.value.to_f self.freeze end end
bonusly/cadooz
lib/cadooz/models/mutable/order.rb
<reponame>bonusly/cadooz class Cadooz::Mutable::Order include ::Mixins attr_accessor :client, :commission, :cost_owner, :cost_unit, :credit_or_number, :customer_reference_number, :delivery_address, :generation_profile, :greeting_card, :invoice_address, :invoice_information, :language, :order_attributes, :order_description, :order_positions, :payment_informations, :queue, :send_mail, :test, :website def initialize(args={}) @client = args[:client] @commission = args[:commission] @cost_owner = args[:cost_owner] @cost_unit = args[:cost_unit] @credit_or_number = args[:credit_or_number] @customer_reference_number = args[:customer_reference_number] @delivery_address = args[:delivery_address] # Cadooz::Mutable::Address.new @generation_profile = args[:generation_profile] @greeting_card = args[:greeting_card] # Cadooz::Mutable::GreetingCard.new @invoice_address = args[:invoice_address] # Cadooz::Mutable::Address.new @invoice_information = Array(args[:invoice_information]) # Cadooz::Mutable::InvoiceInformation @language = args[:language] @order_attributes = args[:order_attributes] @order_description = args[:order_description] @order_positions = Array(args[:order_positions]) # Cadooz::Mutable::OrderPosition @payment_informations = Array(args[:payment_informations]) # Cadooz::Mutable::Payment @queue = args[:queue] @send_mail = args[:send_mail] @test = args[:test] @website = args[:website] end end
bonusly/cadooz
lib/mixins.rb
<filename>lib/mixins.rb module Mixins def serialize(data_only = false) class_name = self.class.to_s.gsub(/Cadooz::[a-z]*::/i, '').underscore result = data_only ? {} : { class_name.to_sym => {} } hash_assign = ->name, value { data_only ? result[name] = value : result[class_name.to_sym][name] = value } self.instance_variables.each do |var| name = var.to_s.gsub('@', '').to_sym value = self.instance_variable_get(var) if value.class.method_defined? :serialize hash_assign.(name, value.serialize(true)) unless instance_variables_empty?(value) elsif value.class == Array arr = [] value.each do |val| arr << val.serialize(true) unless instance_variables_empty?(val) end hash_assign.(name, arr) unless arr.blank? elsif !cadooz_class(value.class) hash_assign.(name, value) unless value.blank? end end result end def instance_variables_empty?(instance) instance.instance_variables.each do |var| return false unless instance.instance_variable_get(var).blank? end true end def cadooz_class(klass) klass = klass.name.split('::').last.to_sym Cadooz.constants.include?(klass) end def default_value_for_nil self.instance_variables.each do |var| value = self.instance_variable_get(var) self.instance_variable_set(var, 'not available') if value.blank? end end end class String def underscore self.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end
bonusly/cadooz
lib/cadooz/models/immutable/attributes.rb
class Cadooz::Immutable::Attributes include Mixins attr_reader :attribute, :values def initialize(open_struct) @attribute = open_struct&.attribute @values = open_struct&.values &.map_entries &.elements &.inject({}) { |hash, element| hash.merge(element.key.to_sym => element.value) } self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/order_position.rb
class Cadooz::Immutable::OrderPosition include Mixins attr_reader :amount, :attributes, :cadooz_product_number, :currency, :delivery_address, :external_reference_number, :greeting_card, :value, :voucher_address, :voucher_address_editable, :voucher_address_preset def initialize(open_struct) @amount = open_struct&.amount @attributes = open_struct&.attributes&.inject({}) { |hash, element| hash.merge(element.key.to_sym => element.value) } @cadooz_product_number = open_struct&.cadooz_product_number @currency = open_struct&.currency @delivery_address = open_struct&.delivery_address @external_reference_number = open_struct&.external_reference_number @greeting_card = open_struct&.greeting_card @value = open_struct&.value @voucher_address = open_struct&.voucher_address @voucher_address_editable = open_struct&.voucher_address_editable @voucher_address_preset = open_struct&.voucher_address_preset self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/order_status.rb
class Cadooz::Immutable::OrderStatus include Mixins attr_reader :delivery_state, :message, :order_number, :order_state, :packet_number, :return_reason, :shipping_provider def initialize(open_struct) @delivery_state = open_struct&.delivery_state @message = open_struct&.message @order_number = open_struct&.order_number @order_state = open_struct&.order_state @packet_number = open_struct&.packet_number @return_reason = open_struct&.return_reason @shipping_provider = open_struct&.shipping_provider self.freeze end end
bonusly/cadooz
lib/cadooz.rb
<gh_stars>1-10 require 'json' require 'money' require 'ostruct' require 'savon' module Cadooz class Configuration attr_accessor :username, :password, :wsdl, :generation_profile, :program_id, :payment_username, :payment_password WSDL = 'https://webservices.cadooz.com/services/businessorder/1.5.2/BusinessOrderService/BusinessOrder?wsdl' TEST_USERNAME = 'cadooz' TEST_PASSWORD = '<PASSWORD>' def initialize(username, password, generation_profile, program_id, payment_username, payment_password) self.username = username || TEST_USERNAME self.password = password || <PASSWORD> self.wsdl = WSDL self.generation_profile = generation_profile self.program_id = program_id self.payment_username = payment_username self.payment_password = <PASSWORD> end end def self.configuration @configuration ||= Configuration.new(nil, nil, nil, nil, nil, nil) end def self.configure yield(configuration) if block_given? end module Immutable end module Mutable end end require_relative 'mixins' require_relative 'cadooz/models/immutable/address' require_relative 'cadooz/models/immutable/attributes' require_relative 'cadooz/models/immutable/catalog' require_relative 'cadooz/models/immutable/catalog_product' require_relative 'cadooz/models/immutable/catalog_product_variation' require_relative 'cadooz/models/immutable/generation_profile_product' require_relative 'cadooz/models/immutable/greeting_card' require_relative 'cadooz/models/immutable/invoice_information' require_relative 'cadooz/models/immutable/order' require_relative 'cadooz/models/immutable/order_position' require_relative 'cadooz/models/immutable/order_status' require_relative 'cadooz/models/immutable/payment' require_relative 'cadooz/models/immutable/product_category' require_relative 'cadooz/models/immutable/response' require_relative 'cadooz/models/immutable/voucher' require_relative 'cadooz/models/immutable/voucher_information' require_relative 'cadooz/models/mutable/address' require_relative 'cadooz/models/mutable/greeting_card' require_relative 'cadooz/models/mutable/invoice_information' require_relative 'cadooz/models/mutable/order' require_relative 'cadooz/models/mutable/order_position' require_relative 'cadooz/models/mutable/payment' require_relative 'cadooz/services/business_order_service'
bonusly/cadooz
lib/cadooz/models/immutable/response.rb
<reponame>bonusly/cadooz class Cadooz::Immutable::Response include Mixins attr_reader :object, :raw def initialize(object, raw_response) @object = object @raw = raw_response self.freeze end end
bonusly/cadooz
lib/cadooz/models/immutable/catalog.rb
<reponame>bonusly/cadooz<filename>lib/cadooz/models/immutable/catalog.rb class Cadooz::Immutable::Catalog include Mixins attr_reader :id, :name, :description, :products def initialize(open_struct) @id = open_struct&.id @name = open_struct&.name @description = open_struct&.description @products = Array(open_struct&.products)&.each_with_object([]) { |p, arr| arr << Cadooz::Immutable::CatalogProduct.new(p) } self.freeze end end
mitixx/abilitysheet
app/controllers/recommends_controller.rb
# frozen_string_literal: true class RecommendsController < ApplicationController before_action :load_color before_action :load_sheets def index @title = '地力値表' end private def load_sheets @sheets = Sheet.active.preload(:ability) end def load_color @color = Static::COLOR end end
mitixx/abilitysheet
db/migrate/20190428173620_change_column_bigint_fk.rb
class ChangeColumnBigintFk < ActiveRecord::Migration[5.2] def change change_column :abilities, :sheet_id, :bigint change_column :follows, :user_id, :bigint change_column :follows, :target_user_id, :bigint change_column :logs, :user_id, :bigint change_column :logs, :sheet_id, :bigint change_column :messages, :user_id, :bigint change_column :scores, :sheet_id, :bigint change_column :scores, :user_id, :bigint end end
mitixx/abilitysheet
app/controllers/scores_controller.rb
# frozen_string_literal: true class ScoresController < ApplicationController before_action :authenticate_user! before_action :check_xhr before_action :load_score before_action :score_exists?, only: %w[edit] def edit @sheet = Sheet.find(params[:id]) @pre_score = current_user.scores.find_by(sheet_id: params[:id], version: Abilitysheet::Application.config.iidx_version - 1) render :show_modal end def update @score.update_with_logs(score_params) render :reload end private def score_exists? return if @score @score = current_user.scores.create!(version: Abilitysheet::Application.config.iidx_version, sheet_id: params[:id]) end def load_score version = Abilitysheet::Application.config.iidx_version parameters = { version: version } if params[:action] == 'edit' parameters[:sheet_id] = params[:id] else parameters[:id] = params[:id] end @score = current_user.scores.find_by(parameters) end def score_params params.require(:score).permit( :sheet_id, :state ) end end
mitixx/abilitysheet
app/helpers/application_helper.rb
# frozen_string_literal: true module ApplicationHelper def return_ability_rival(cnt) params[:action] == 'clear' ? @sheets[cnt].n_ability : @sheets[cnt].h_ability end def adsense(slot = 2) react_component_wrapper 'Adsense', slot: slot end def react_component_wrapper(component, props = {}) props[:context] = { sentry_dsn: ENV['SENTRY_JS_DSN'] } react_component component, props end def render_ads? return true unless current_user !(current_user.special? || current_user.owner?) end def recent_link(iidxid) user = User.find_by_iidxid(iidxid) return false unless user return false if user.logs.empty? logs_path(user.iidxid, user.logs.order(:created_date).last.created_date) end def icon(name, text = nil, html_options = {}, style: 'fas') if text.is_a?(Hash) html_options = text text = nil end content_class = "#{style} fa-#{name}" content_class << " #{html_options[:class]}" if html_options.key?(:class) html_options[:class] = content_class html = content_tag(:i, nil, html_options) html << ' ' << text.to_s unless text.blank? html end end
mitixx/abilitysheet
spec/systems/logs/sheet_spec.rb
# frozen_string_literal: true feature '推移ログ', type: :system, js: true do given(:user) { create(:user, id: 1) } context 'ログが存在しない場合' do context 'ログイン時' do background do login(user) visit sheet_log_path(user.iidxid) end scenario 'クリア推移表の文字列が存在する' do expect(page).to have_content('クリア推移表') end end context '非ログイン時' do background do visit sheet_log_path(user.iidxid) end scenario 'クリア推移表の文字列が存在する' do expect(page).to have_content('クリア推移表') end end end context 'ログが存在する場合' do background do create(:sheet, id: 1, title: 'graph', active: true) create(:log, sheet_id: 1, user_id: 1, pre_state: 6, new_state: 6) end context 'ログイン時' do background do login(user) visit sheet_log_path(user.iidxid) end scenario '推移ページが表示できる' do expect(page).to have_content('クリア推移表') end end context '非ログイン時' do background do visit sheet_log_path(user.iidxid) end scenario '推移ページが表示できる' do expect(page).to have_content('クリア推移表') end end end end
mitixx/abilitysheet
app/jobs/sync_sheets_job.rb
# frozen_string_literal: true require 'ist_client' class SyncSheetsJob < ApplicationJob queue_as :system def perform(date = Date.today - 2.days) client = IstClient.new sheets = client.get_musics( q: { charts_play_type_status_eq: 0, charts_level_eq: 12, charts_updated_at_gteq: date } ) sheets.each do |sheet| sheet['charts'].each do |chart| title = sheet['title'] title += '†' if chart['difficulty_type_status'] == 'LEGGENDARIA' s = Sheet.find_by(title: title) next if s Sheet.create!( title: title, version: sheet['version_status_before_type_cast'], n_ability: Static::POWER.last[1], h_ability: Static::POWER.last[1], exh_ability: Static::EXH_POWER.last[1], textage: '' ) end end Sheet.apply_exh end end
mitixx/abilitysheet
app/controllers/admin/messages_controller.rb
# frozen_string_literal: true class Admin::MessagesController < ApplicationController before_action :authenticate_user! before_action :admin_user! before_action :load_message, except: [:index] def index @search = Message.ransack(params[:q]) @messages = @search.result end def active @message.update!(state: true) redirect_to admin_messages_path end def inactive @message.update!(state: false) redirect_to admin_messages_path end private def load_message return unless params[:id] @message = Message.find_by(id: params[:id]) end end
mitixx/abilitysheet
app/jobs/version_up_job.rb
<filename>app/jobs/version_up_job.rb # frozen_string_literal: true class VersionUpJob < ApplicationJob queue_as :system def perform User.version_up! end end
mitixx/abilitysheet
spec/decorators/mail_decorator_spec.rb
# frozen_string_literal: true describe MailDecorator do end
mitixx/abilitysheet
lib/scrape/exh_collector.rb
# frozen_string_literal: true require 'open-uri' module Scrape class ExhCollector def initialize @url = 'https://www65.atwiki.jp/sp12ex-hard/pages/12.html' end def get_sheet text = URI.open(@url).read # rubocop:disable all html = Nokogiri::HTML.parse(text) parse(html) end private def parse(html) result = {} tables = html.xpath('//table') headers = html.xpath('//h2') tables.each_with_index do |table, index| header = headers[index + 1] table.children.each do |row| title = row.children[5]&.text next if title == '曲名' next unless title result[title] = header.text end end result end end end
mitixx/abilitysheet
spec/decorators/message_decorator_spec.rb
<reponame>mitixx/abilitysheet<gh_stars>10-100 # frozen_string_literal: true describe MessageDecorator do before { create(:user, id: 1) } describe '#user_name' do context 'user_idが指定されていない' do it '匿名と表示' do message = build_stubbed(:message).decorate expect(message.user_name).to eq '匿名' end end context 'user_idが指定されている' do it 'djname[iidxid]の書式で表示' do message = build_stubbed(:message, user_id: 1).decorate expect(message.user_name).to eq 'TEST[1234-5678]' end end end describe '#status' do context '未チェック' do it '未読を表示' do message = build_stubbed(:message, state: false).decorate expect(message.status).to eq '未読' end end context 'チェック済' do it '既読を表示' do message = build_stubbed(:message, state: true).decorate expect(message.status).to eq '既読' end end end describe '#created_at' do context '作成日がnilの場合' do it '現在日時を整形して表示' do message = build_stubbed(:message, created_at: nil).decorate expect(message.created_at).to eq Time.now.strftime('%Y/%m/%d %H:%M') end end context '作成日が存在する場合' do it '存在する日を整形して表示' do message = build_stubbed(:message, created_at: '2011-02-22 22:22').decorate expect(message.created_at).to eq '2011/02/22 22:22' end end end end
mitixx/abilitysheet
app/models/user.rb
<reponame>mitixx/abilitysheet # frozen_string_literal: true # == Schema Information # # Table name: users # # id :bigint(8) not null, primary key # email :string default(""), not null # username :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 :inet # last_sign_in_ip :inet # iidxid :string not null # version :integer default(22), not null # djname :string not null # grade :integer # pref :integer not null # role :integer default(0), not null # failed_attempts :integer default(0), not null # unlock_token :string # locked_at :datetime # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_users_on_iidxid (iidxid) UNIQUE # index_users_on_reset_password_token (reset_password_token) UNIQUE # index_users_on_unlock_token (unlock_token) UNIQUE # index_users_on_username (username) UNIQUE # class User < ApplicationRecord devise :database_authenticatable, :registerable, :omniauthable, :rememberable, :recoverable, :trackable, :validatable, :lockable attr_accessor :login has_one_attached :avatar include User::Api include User::DeviseMethods include User::FollowMethods include User::List include User::Role include User::Static include User::Ist has_many :scores, dependent: :delete_all has_many :logs, dependent: :delete_all has_many :follows, dependent: :delete_all has_many :followers, foreign_key: :target_user_id, class_name: 'Follow', dependent: :delete_all has_many :follow_users, through: :follows, source: :to_user has_many :follower_users, through: :followers, source: :from_user has_many :messages, dependent: :delete_all has_many :socials, dependent: :delete_all validates :email, uniqueness: true, presence: true, format: { with: Devise.email_regexp, message: 'が正しくありません。' } validates :iidxid, format: { with: /\A\d{4}-\d{4}\z/, message: 'が正しくありません。' }, length: { is: 9 }, uniqueness: true, presence: true validates :grade, numericality: { only_integer: true }, inclusion: { in: Abilitysheet::Application.config.iidx_grade..19, message: 'のパラメタが異常です。' }, presence: true validates :pref, numericality: { only_integer: true }, inclusion: { in: 0..User::Static::PREF.size, message: 'のパラメタが異常です。' }, presence: true validates :djname, length: { maximum: 6 }, format: { with: /\A[A-Z0-9\-_.*!#&$]+\z/, message: 'は半角大文字英字で記入して下さい' }, presence: true validates :username, length: { maximum: 15 }, format: { with: /\A[a-z_0-9]+\z/, message: 'は半角小文字英数字で記入して下さい' }, uniqueness: true, presence: true # iidx_versionが新しくなってから実行する def version_up! update_column(:grade, GRADE.size - 1) current_version = Abilitysheet::Application.config.iidx_version return if scores.where(version: current_version).count == scores.where(version: current_version - 1).count ApplicationRecord.transaction do new_scores = [] now = Time.now scores.select(:sheet_id, :state, :version).where(version: current_version - 1).each do |score| new_score = scores.find { |s| s.version == current_version && s.sheet_id == score.sheet_id } next if new_score new_scores.push( state: score.state, sheet_id: score.sheet_id, user_id: id, version: current_version, created_at: now, updated_at: now ) if (new_scores.count % 1000).zero? Score.insert_all!(new_scores) new_scores = [] end end Score.insert_all!(new_scores) unless new_scores.count.zero? end end def pref_name User::Static::PREF[pref] end class << self def find_for_oauth(auth, user) social = Social.find_by(uid: auth.uid, provider: auth.provider) if social social.update!( uid: auth.uid, provider: auth.provider, token: auth.credentials.token, secret: auth.credentials.secret, raw: JSON.parse(auth.to_json) ) return social.user end return unless user user.socials.create!( uid: auth.uid, provider: auth.provider, token: auth.credentials.token, secret: auth.credentials.secret, raw: JSON.parse(auth.to_json) ) user end def dan array = [] Static::GRADE.each.with_index(0) { |d, i| array.push([d, i]) if Abilitysheet::Application.config.iidx_grade <= i } array end def belongs array = [] Static::PREF.each_with_index { |p, i| array.push([p, i]) } array end def version_up! users_count = count logger.info("start: #{Time.now}, users: #{users_count}") completed_count = 0 all.find_each do |user| user.version_up! completed_count += 1 logger.info("completed count: #{completed_count}") if (completed_count % 100).zero? end logger.info("done: #{Time.now}, users: #{users_count}") end end end
mitixx/abilitysheet
spec/services/clearing_transition_table_service_spec.rb
# frozen_string_literal: true describe ClearingTransitionTableService, type: :service do let(:user) { create(:user) } let(:sheet) { create(:sheet, active: true) } it 'ログの状態から正しく楽曲の推移hashが作れること' do user.logs.create!(sheet_id: sheet.id, pre_state: 4, new_state: 3, created_date: Date.today - 1.day) user.logs.create!(sheet_id: sheet.id, pre_state: 3, new_state: 1, created_date: Date.today) expect(ClearingTransitionTableService.new(user).execute).to eq( sheet.title => { 3 => Date.today - 1.day, 1 => Date.today } ) end it '楽曲のクリア状態が戻された場合は後の日付を優先すること' do user.logs.create!(sheet_id: sheet.id, pre_state: 4, new_state: 3, created_date: Date.today - 2.day) user.logs.create!(sheet_id: sheet.id, pre_state: 3, new_state: 4, created_date: Date.today - 1.day) user.logs.create!(sheet_id: sheet.id, pre_state: 4, new_state: 3, created_date: Date.today) expect(ClearingTransitionTableService.new(user).execute).to eq( sheet.title => { 4 => Date.today - 1.day, 3 => Date.today } ) end end
mitixx/abilitysheet
config/routes.rb
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html devise_for :users, controllers: { registrations: 'users/registrations', passwords: '<PASSWORD>', omniauth_callbacks: 'users/omniauth_callbacks' } resources :google, only: :destroy, param: :iidxid # all visitor root 'welcomes#index' resources :users, only: %i(index show) resources :messages, only: [:new, :create] resources :helps, only: [] do collection do get :support get :ist get :oauth end end # admin require 'sidekiq/web' authenticate :user, ->(u) { u.admin? } do mount RailsAdmin::Engine => '/admin/model', as: :rails_admin mount Sidekiq::Web => '/admin/sidekiq/dashboard', as: :sidekiq_admin end namespace :admin do resources :dashboards, only: :index resources :socials, only: %i[index show] post '/sheets/diff', to: 'sheets#diff' resources :sheets do post :active, on: :member post :inactive, on: :member end resources :users do post :lock, on: :member post :unlock, on: :member get :login, on: :member end resources :messages, only: :index do post :active, on: :member post :inactive, on: :member end resources :mails, only: %i(new create) end # rival get '/rival/list' => 'rivals#list', as: :list_rival get '/rival/reverse_list' => 'rivals#reverse_list', as: :reverse_list_rival get '/rival/clear/:id' => 'rivals#clear', as: :clear_rival get '/rival/hard/:id' => 'rivals#hard', as: :hard_rival post '/rival/remove/:id' => 'rivals#remove', as: :remove_rival post '/rival/register/:id' => 'rivals#register', as: :register_rival resources :rivals, only: [] do put 'reverse' end # sheet get '/sheets/:iidxid/:type' => 'sheets#show', as: :sheet # score resources :scores, only: %i(edit update) # log resources :logs, only: %i(edit update destroy) do get :list, on: :member get :sheet, on: :member post :ist, on: :member end get '/logs/:id/:date' => 'logs#show', as: :logs # recommends resources :recommends, only: :index # API namespace :api do namespace :v1 do resources :abilities, only: %i[index create] # users resources :users, only: [] do collection do get :status get :me put '/users/change_rival/:iidxid', to: 'users#change_rival' end end # messages resources :messages, only: :index # logs resources :logs, only: [], param: :iidxid do get :cal_heatmap end get '/logs/:log_iidxid/:year/:month' => 'logs#full_calendar' get '/logs/graph/:log_iidxid/:year/:month' => 'logs#graph' # statics resources :statics, only: :index # sheets resources :sheets, only: :index get '/sheets/list' => 'sheets#list' # scores resources :scores, only: :show, param: :iidxid get '/scores/:iidxid/:sheet_id' => 'scores#detail' put '/scores/:iidxid/:sheet_id/:state' => 'scores#update' post '/maintenance', to: 'maintenance#change' resources :health_check, only: :index end end mount Sidekiq::Prometheus::Exporter => '/sidekiq/metrics' end
mitixx/abilitysheet
app/controllers/admin/users_controller.rb
# frozen_string_literal: true class Admin::UsersController < ApplicationController before_action :authenticate_user! before_action :admin_user! before_action :check_xhr, except: %i[index login] before_action :load_user, except: %i[index new create] def index @q = User.ransack(params[:q]) @q.sorts = ['id desc'] if @q.sorts.empty? @users = @q.result.page(params[:page]) end def new render :show_modal_form end def create @user = User.new(user_params) @user.save render :reload end def edit render :show_modal_form end def update @user.update_without_current_password(user_params) render :reload end def destroy @user.destroy render :reload end def lock @user.lock_access! render :reload end def unlock @user.unlock_access! render :reload end def login sign_out current_user sign_in @user redirect_to root_path end private def user_params params.require(:user).permit( :email, :iidxid, :username, :djname, :grade, :pref, :password ) end def load_user return unless params[:id] @user = User.find_by(id: params[:id]) end end
mitixx/abilitysheet
app/mailers/devise/mailer.rb
# frozen_string_literal: true class Devise::Mailer < Devise.parent_mailer.constantize include Devise::Mailers::Helpers def reset_password_instructions(record, token, opts = {}) @token = token devise_mail(record, :reset_password_instructions, opts) end def unlock_instructions(record, token, opts = {}) return if record.email.empty? @token = token devise_mail(record, :unlock_instructions, opts) end def password_change(record, opts = {}) devise_mail(record, :password_change, opts) end end
mitixx/abilitysheet
spec/models/log_spec.rb
# frozen_string_literal: true # == Schema Information # # Table name: logs # # id :bigint(8) not null, primary key # user_id :bigint(8) # sheet_id :bigint(8) # pre_state :integer # new_state :integer # pre_score :integer # new_score :integer # pre_bp :integer # new_bp :integer # version :integer # created_date :date # # Indexes # # index_logs_on_created_date_and_user_id_and_sheet_id (created_date,user_id,sheet_id) UNIQUE # index_logs_on_sheet_id (sheet_id) # index_logs_on_user_id (user_id) # describe Log, type: :model do describe '.cleanup!' do before do create(:user, id: 1) create(:sheet, id: 1) create(:log, id: 1, user_id: 1, sheet_id: 1, pre_bp: 22, new_bp: 25, pre_score: 140, new_score: 120, created_date: '2000-01-01') create(:log, id: 2, user_id: 1, sheet_id: 1, pre_bp: 22, new_bp: 20, pre_score: 140, new_score: 140, created_date: '2000-01-02') create(:log, id: 3, user_id: 1, sheet_id: 1, pre_bp: 22, new_bp: 15, pre_score: 140, new_score: 160, created_date: '2000-01-03') end it 'ログデータのスコアが正しい数値に整形される' do User.find(1).logs.cleanup!(Abilitysheet::Application.config.iidx_version) expect(Log.exists?(id: 1, pre_bp: 22, new_bp: 25, pre_score: 140, new_score: 120)).to eq true expect(Log.exists?(id: 2, pre_bp: 25, new_bp: 20, pre_score: 120, new_score: 140)).to eq true expect(Log.exists?(id: 3, pre_bp: 20, new_bp: 15, pre_score: 140, new_score: 160)).to eq true end end describe '.attributes' do before { create(:sheet, id: 1) } let(:parameter) do { 'sheet_id' => 1, 'state' => 5 } end let(:user) { create(:user, id: 1) } context '初めての更新の場合' do it 'ログデータが作られる' do expect { user.logs.attributes(parameter, user) }.to change(Log, :count).by(1) expect(user.logs.exists?(sheet_id: 1, pre_state: 7, new_state: 5)).to eq true end end context '同日に同じ楽曲を更新する場合' do before { user.logs.attributes(parameter, user) } it 'ログデータは更新される' do expect { user.logs.attributes({ 'sheet_id' => 1, 'state' => 0 }, user) }.to change(Log, :count).by(0) expect(user.logs.exists?(sheet_id: 1, pre_state: 7, new_state: 0)).to eq true end end context '違う日に同じ楽曲を更新する場合' do before { create(:log, user_id: 1, sheet_id: 1, created_date: Date.today - 1, pre_state: 7, new_state: 6) } it 'ログデータが作られる' do create(:score, user_id: 1, sheet_id: 1, state: 6) expect { user.logs.attributes(parameter, user) }.to change(Log, :count).by(1) expect(user.logs.exists?(sheet_id: 1, pre_state: 7, new_state: 6)).to eq true expect(user.logs.exists?(sheet_id: 1, pre_state: 6, new_state: 5)).to eq true end end end describe '.prev_next' do before do create(:log, created_date: '2015/09/30', user_id: 1) create(:log, created_date: '2015/08/30', user_id: 2) create(:log, created_date: '2015/07/30', user_id: 1) create(:log, created_date: '2015/07/20', user_id: 2) create(:log, created_date: '2015/06/30', user_id: 1) end it '間に他のユーザのデータが有ってもログの前後関係が正しい' do expect(Log.prev_next(1, '2015/07/30')).to eq ['2015/06/30'.to_date, '2015/09/30'.to_date] end it '先頭のデータの場合,prevにnilを返す' do expect(Log.prev_next(1, '2015/06/30')).to eq [nil, '2015/07/30'.to_date] end it '末尾のデータの場合,nextにnilを返す' do expect(Log.prev_next(1, '2015/09/30')).to eq ['2015/07/30'.to_date, nil] end end end
mitixx/abilitysheet
spec/systems/logs/list_spec.rb
# frozen_string_literal: true feature 'ログ一覧', type: :system do given(:user) { create(:user, id: 1) } background do login(user) visit list_log_path(user.iidxid) end scenario 'ログ一覧ページが閲覧できる' do expect(page).to have_content('更新履歴') end end
mitixx/abilitysheet
app/decorators/user_decorator.rb
<filename>app/decorators/user_decorator.rb # frozen_string_literal: true class UserDecorator < Draper::Decorator delegate_all def pref User::Static::PREF[object.pref] end def grade User::Static::GRADE[object.grade] end def belongs User::Static::PREF[object.pref] end def dan User::Static::GRADE[object.grade] end def joined_on "Joined on #{object.created_at.to_s.split.first.tr('-', '/')}" end def dan_color return '#afeeee' if object.grade >= 3 && object.grade <= 10 return '#ff6347' if object.grade == 1 || object.grade == 2 return '#ffd900' if object.grade.zero? '#98fb98' end def current return '未ログイン' unless object.current_sign_in_at "#{object.current_sign_in_at.strftime('%Y/%m/%d %H:%M')}/#{object.current_sign_in_ip}" end def last return '未ログイン' unless object.last_sign_in_at "#{object.last_sign_in_at.strftime('%Y/%m/%d %H:%M')}/#{object.last_sign_in_ip}" end end
mitixx/abilitysheet
app/controllers/sheets_controller.rb
<gh_stars>10-100 # frozen_string_literal: true class SheetsController < ApplicationController before_action :load_user before_action :check_action, except: %i[change_reverse detail] def show load_static unless params[:type] == 'power' # FIXME: params[:type]から判別できるのでpower以外はコントローラ通さなくて良い # フロント部分も結構変更が必要かも __send__(@action_routes[params[:type]]) render @action_routes[params[:type]] end private def check_action @action_routes = { 'power' => :power, 'clear' => :clear, 'hard' => :hard, 'exh' => :exh } raise ActionController::RoutingError, "No route matches #{request.path.inspect}" unless @action_routes[params[:type]] end def power @sheets = Sheet.active.preload(:ability) @color = Score.convert_color(@user.scores.is_current_version) end def clear; end def hard; end def exh; end def load_user @user = User.find_by_iidxid!(params[:iidxid]) end def load_static @versions = Static::VERSION.dup @versions.push(['ALL', 0]) end end
mitixx/abilitysheet
db/seeds.rb
<reponame>mitixx/abilitysheet uri = URI.parse('https://sp12.iidx.app/api/v1/sheets/list') sheets = JSON.parse(Net::HTTP.get(uri)) sheets['sheets'].each { |sheet| Sheet.create(sheet) }
mitixx/abilitysheet
app/controllers/messages_controller.rb
<filename>app/controllers/messages_controller.rb # frozen_string_literal: true require 'slack/message_dispatcher' class MessagesController < ApplicationController def new @message = Message.new end def create message = Message.new(message_params) message.user_id = current_user.id if user_signed_in? message.ip = request.remote_ip result = message.save if result Slack::MessageDispatcher.send(message.id) flash[:notice] = '承りました。対応はしばしお待ちください。' else flash[:danger] = '何らかの不具合で送信できていません。Twitterなどにご連絡下さい。' end redirect_to root_path end def password; end private def message_params params.require(:message).permit( :email, :body ) end end
mitixx/abilitysheet
app/controllers/api/v1/users_controller.rb
# frozen_string_literal: true class Api::V1::UsersController < Api::V1::BaseController def status render json: { status: current_user.try(:iidxid) } end def me render json: { current_user: current_user.try(:schema) } end end
mitixx/abilitysheet
app/models/log.rb
# frozen_string_literal: true # == Schema Information # # Table name: logs # # id :bigint(8) not null, primary key # user_id :bigint(8) # sheet_id :bigint(8) # pre_state :integer # new_state :integer # pre_score :integer # new_score :integer # pre_bp :integer # new_bp :integer # version :integer # created_date :date # # Indexes # # index_logs_on_created_date_and_user_id_and_sheet_id (created_date,user_id,sheet_id) UNIQUE # index_logs_on_sheet_id (sheet_id) # index_logs_on_user_id (user_id) # class Log < ApplicationRecord belongs_to :user belongs_to :sheet delegate :title, to: :sheet validates :sheet_id, uniqueness: { scope: %i[created_date user_id] } after_destroy :rollback_score include Graph def self.prev_next(user_id, date) p = where(user_id: user_id).order(created_date: :desc).find_by('created_date < ?', date).try(:created_date) n = where(user_id: user_id).order(:created_date).find_by('created_date > ?', date).try(:created_date) [p, n] end def self.attributes(score_params, owner) return score_attributes(score_params, owner) if score_params['score'] && score_params['bp'] log = find_by(sheet_id: score_params['sheet_id'], created_date: Date.today) if log log.update!(new_state: score_params['state']) return true end pre_state = owner.scores.find_by(sheet_id: score_params['sheet_id']).try(:state) || 7 # スコアBPの更新がなく,状態が変わっていない場合はログを作らない return false if pre_state == score_params['state'].to_i owner.logs.create!( sheet_id: score_params['sheet_id'], pre_state: pre_state, new_state: score_params['state'], pre_score: nil, new_score: nil, pre_bp: nil, new_bp: nil, version: Abilitysheet::Application.config.iidx_version, created_date: Date.today ) end def self.score_attributes(score_params, owner) log = find_by(sheet_id: score_params['sheet_id'], created_date: Date.today) if log log.update!(new_score: score_params['score'], new_bp: score_params['bp']) return true end now_score = owner.scores.is_current_version.find_by(sheet_id: score_params['sheet_id']) pre_state = now_score.try(:state) || 7 owner.logs.create!( sheet_id: score_params['sheet_id'], pre_state: pre_state, new_state: score_params['state'], pre_score: now_score.score, new_score: score_params['score'], pre_bp: now_score.bp, new_bp: score_params['bp'], version: Abilitysheet::Application.config.iidx_version, created_date: Date.today ) end # Usage: User.first.logs.cleanup!(23) def self.cleanup!(version) logs = where(version: version) Sheet.all.each do |sheet| logs.where(sheet_id: sheet.id).order(:created_date).each_cons(2) do |p_log, n_log| n_log.update!(pre_score: p_log.new_score, pre_bp: p_log.new_bp) end end end def schema { state: new_state, title: title, created_date: created_date } end private def rollback_score score = Score.find_by(user_id: user_id, sheet_id: sheet_id, version: Abilitysheet::Application.config.iidx_version) score.update!(state: pre_state, score: pre_score, bp: pre_bp) end end
mitixx/abilitysheet
app/controllers/rivals_controller.rb
<filename>app/controllers/rivals_controller.rb<gh_stars>10-100 # frozen_string_literal: true class RivalsController < ApplicationController before_action :authenticate_user! before_action :load_sheet, only: %i[clear hard] def list @users = current_user.follow_users load_rival end def reverse_list @users = current_user.follower_users load_rival end def clear @sheets = @sheets.active.order(:n_ability, :title) return if params[:condition] == 'all' condition if params[:condition] end def hard @sheets = @sheets.order(:h_ability, :title) return if params[:condition] == 'all' condition if params[:condition] end def reverse target_user = User.find_by!(iidxid: params[:rival_id]) current_user.change_follow(target_user) redirect_back(fallback_location: root_path) end def register current_user.follow(params[:id]) ? flash[:notice] = "ライバル(#{params[:id]})を追加しました" : flash[:danger] = '既に登録済みのライバルです' render :reload end def remove current_user.unfollow(params[:id]) ? flash[:notice] = "ライバル(#{params[:id]})を削除しました" : flash[:danger] = 'ライバルに登録されていません' render :reload end private def load_rival @scores_map = User.users_list(:rivals, @users) @color = Static::COLOR end def condition copy = @sheets @sheets = [] rival_id = User.find_by_iidxid!(params[:id]).id copy.each { |sheet| copy_sheets(sheet, rival_id) } end def copy_sheets(sheet, rival_id) m_state = sheet.scores.is_current_version.find_by_user_id(current_user.id).try(:state) || 7 r_state = sheet.scores.is_current_version.find_by_user_id(rival_id).try(:state) || 7 @sheets.push(sheet) if params[:condition] == 'win' && m_state < r_state @sheets.push(sheet) if params[:condition] == 'even' && m_state == r_state @sheets.push(sheet) if params[:condition] == 'lose' && m_state > r_state end def load_sheet @sheets = Sheet.active @state_examples = {} 7.downto(0) { |j| @state_examples[Score.list_name[j]] = Static::COLOR[j] } @power = Static::POWER.dup s = User.find_by_iidxid!(params[:id]).scores.is_current_version @rival_color = Score.convert_color(s) s = current_user.scores.is_current_version @my_color = Score.convert_color(s) @list_color = Static::COLOR end end
mitixx/abilitysheet
spec/models/score_spec.rb
# frozen_string_literal: true # == Schema Information # # Table name: scores # # id :bigint(8) not null, primary key # state :integer default(7), not null # score :integer # bp :integer # sheet_id :bigint(8) not null # user_id :bigint(8) not null # version :integer not null # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_scores_on_sheet_id (sheet_id) # index_scores_on_updated_at (updated_at) # index_scores_on_user_id (user_id) # index_scores_on_user_id_and_version_and_updated_at (user_id,version,updated_at) # index_scores_on_version_and_sheet_id_and_user_id (version,sheet_id,user_id) UNIQUE # describe Score, type: :model do before do create(:sheet, id: 1, title: 'one', active: true) create(:sheet, id: 2, title: 'two', active: true) create(:sheet, id: 3, title: 'three') @user = create(:user, id: 1) create(:score, id: 1, user_id: 1, sheet_id: 1, state: 7, updated_at: '2015-06-23 15:34') create(:score, id: 2, user_id: 1, sheet_id: 2, state: 7, updated_at: '2015-06-23 15:35') create(:score, id: 3, user_id: 1, sheet_id: 3, state: 7, updated_at: '2015-06-23 15:35') Score.find(1).update_with_logs(sheet_id: 1, state: 6, score: 100, bp: 5) end describe '#remain' do it '未難の数を正しく返す' do expect(@user.scores.remain(:hard)).to eq Sheet.active.count Score.find(1).update!(state: 5) expect(@user.scores.remain(:hard)).to eq Sheet.active.count Score.find(1).update!(state: 2) expect(@user.scores.remain(:hard)).to eq Sheet.active.count - 1 expect(@user.scores.remain_string(:hard)).to eq "☆12ハード参考表(未難#{Sheet.active.count - 1})" end it '未クリアの数を正しく返す' do expect(@user.scores.remain(:clear)).to eq Sheet.active.count Score.find(1).update!(state: 6) expect(@user.scores.remain(:clear)).to eq Sheet.active.count Score.find(1).update!(state: 4) expect(@user.scores.remain(:clear)).to eq Sheet.active.count - 1 expect(@user.scores.remain_string(:clear)).to eq "☆12ノマゲ参考表(未クリア#{Sheet.active.count - 1})" end end describe '.last_updated' do it '新しい順かつNOPLAYではないスコアを返す' do expect(@user.scores.last_updated.id).to eq 1 end end describe '.is_active' do it 'アクティブな楽曲のスコア一覧を返す' do expect(@user.scores.is_active.count).to eq 2 end end describe '#active?' do it 'activeな曲はtrueを返す' do expect(Score.find_by(id: 1).active?).to eq true end it 'inactiveな曲はfalseを返す' do expect(Score.find_by(id: 3).active?).to eq false end end describe '#update_with_logs' do it 'logデータも作られている' do @user.scores.find_by(id: 1).update_with_logs(sheet_id: 1, state: 5) ret = { user_id: 1, sheet_id: 1, pre_state: 7, new_state: 5, pre_score: nil, new_score: 100, pre_bp: nil, new_bp: 5 } expect(@user.logs.exists?(ret)).to eq true end it '状態が変化しない場合はupdateされない' do score_params = { 'sheet_id' => '1', 'state' => '6' } expect(@user.scores.find_by(id: 1).update_with_logs(score_params)).to be_falsy end context '一部の状態が変化する場合' do it 'scoreのみが変化する' do expect(@user.logs.exists?(sheet_id: 1, pre_state: 7, new_state: 6, new_score: 100, new_bp: 5)).to be_truthy @user.scores.find_by(id: 1).update_with_logs(sheet_id: 1, state: 6, score: 101, bp: 5) expect(@user.logs.exists?(sheet_id: 1, pre_state: 7, new_state: 6, pre_score: nil, new_score: 101, new_bp: 5)).to be_truthy end it 'bpのみが変化する' do expect(@user.logs.exists?(sheet_id: 1, pre_state: 7, new_state: 6, new_score: 100, new_bp: 5)).to be_truthy @user.scores.find_by(id: 1).update_with_logs(sheet_id: 1, state: 6, score: 100, bp: 101) expect(@user.logs.exists?(sheet_id: 1, pre_state: 7, new_state: 6, pre_bp: nil, new_bp: 101)).to be_truthy end end end context 'validate' do context '一つのバージョンでユーザは同じ楽曲を複数持たない' do it 'rails側のvalidationに引っかかること' do expect do Score.create(id: 99, user_id: 99, sheet_id: 1, version: 1) Score.create(id: 100, user_id: 99, sheet_id: 1, version: 1) end.to change(Score, :count).by(1) end it 'rdb側のvalidationに引っかかること' do expect do Score.create(id: 99, user_id: 99, sheet_id: 1, version: 1) score = Score.new(id: 100, user_id: 99, sheet_id: 1, version: 1) begin score.save(validate: false) rescue ActiveRecord::RecordNotUnique => e expect(e.message.include?('PG::UniqueViolation: ERROR: duplicate key value violates unique constraint')).to eq true end end.to change(Score, :count).by(1) end end end end