text
stringlengths
10
2.61M
class TocatRoleSerializer < ActiveModel::Serializer include Rails.application.routes.url_helpers attributes :id, :name, :position, :permissions, :links private def links data = {} if object.id data[:href] = tocat_role_path(object) data[:rel] = 'self' end data end end
class CareerStat < ApplicationRecord belongs_to :player validates_uniqueness_of :player_id end
def roll_call_dwarves(names) # Your code here names.each_with_index do |name, index| puts "#{index + 1} #{name}" end end def summon_captain_planet(calls) # Your code here calls.collect do |call| call.capitalize + "!" end end def long_planeteer_calls(calls) # Your code here calls.any? do |call| call.length > 4 end end def find_the_cheese(strings) # the array below is here to help cheese_types = ["cheddar", "gouda", "camembert"] strings.find do |string| string == (cheese_types[0] || cheese_types[1] || cheese_types[2]) end end
module ApplicationHelper # Method used to "present" an object with its associated presenter. def present(object, klass = nil) klass ||= "#{object.class}Presenter".constantize presenter = klass.new(object, self) yield presenter if block_given? presenter end def first_image_url(html_string) image = Nokogiri::HTML.parse(html_string).css("img").first image['src'] unless image.nil? end end
class SentencesController < ApplicationController def create story = Story.find(params[:story_id]) story.sentences.create( user: current_user, body: sentence_params[:body].squish ) redirect_to story end def vote story = Story.find(params[:story_id]) sentence = story.sentences.find(params[:id]) sentence.votes << current_user.id sentence.update_current_winner unless sentence.winner? sentence.save redirect_to story end def sentence_params params.require(:sentence).permit :id, :body, :story_id end end
require 'pony' module EnglishGate class EmailNotifier < EnglishGate::Notifier attr_accessor :subject def send Pony.mail({ :from => @from, :to => @to, :subject => @subject, :body => @message, :charset => 'utf-8', :via => :smtp, :via_options => { :address => ENV['SMTP_ADDRESS'], :port => ENV['SMTP_PORT'], :enable_starttls_auto => true, :user_name => ENV['SMTP_USERNAME'], :password => ENV['SMTP_PASSWORD'], :authentication => :plain, # :plain, :login, :cram_md5, no auth by default :domain => 'localhost.localdomain' # the HELO domain provided by the client to the server } }) end end end
module OpenAPIParser::Parser::Value def _openapi_attr_values @_openapi_attr_values ||= {} end def openapi_attr_values(*names) names.each { |name| openapi_attr_value(name) } end def openapi_attr_value(name, options = {}) target_klass.send(:attr_reader, name) _openapi_attr_values[name] = OpenAPIParser::SchemaLoader::ValuesLoader.new(name, options) end end
#!/usr/bin/env ruby # vim: noet module Fuzz::Token class Gender < Base Male = ["male", "man", "boy", "m"] Female = ["female", "woman", "girl", "f"] Pattern = (Male + Female).join("|") # whatever variation of gender was # matched, return a regular symbol def normalize(gender_str) Male.include?(gender_str.downcase) ? (:male) : (:female) end Examples = { "male" => :male, "female" => :female, "boy" => :male, "girl" => :female } end end
class UsersController < ApplicationController # GET /users # GET /users.xml before_filter :check_login_status def search @search_string = params[:search][:title] # @user = User.find(session[:user_id]) puts "===> inside /user/search search string = " + @search_string @users = User.find(:all, :conditions => ['user_name LIKE ? OR email LIKE?', "%#{params[:search][:title]}%", "%#{params[:search][:title]}%"]); puts "===> inside /user/search search result = " render :file => "/users/index" end def tag @user = User.find(session[:user_id]) @tag = Tag.find(params[:id]) @blogs = @tag.blogs @search = Blog.new render :file => "users/show" end def start @user = User.new respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users } end end def index @users = User.find(:all,:order => 'user_name ASC') respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users } end end # GET /users/1 # GET /users/1.xml def show if((@user = User.find_by_user_name(params[:id]))==nil) @user = User.find(params[:id]) end @blogs = @user.blogs @search = Blog.new # @search.user_id = session[:user_id] # puts "/users/show: session[:user_id] = " + session[:user_id].to_s respond_to do |format| format.html # show.html.erb end end # GET /users/new # GET /users/new.xml def new @user = User.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @user } end end # GET /users/1/edit def edit @user_id = params[:id] # if ( session[:user_id] == @user_id) @user = User.find(@user_id) # end end def remote_edit_user @user = User.find(params[:id]) render :text => "i dont know" end # POST /users # POST /users.xml def create @user = User.new(params[:user]) respond_to do |format| if @user.save session[:user_id] = @user.id format.html { redirect_to(user_path(@user.id), :notice => 'User was successfully created.') } format.xml { render :xml => @user, :status => :created, :location => @user } else format.html { render :action => "new" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end # PUT /users/1 # PUT /users/1.xml def update @user = User.find(params[:id]) respond_to do |format| if @user.update_attributes(params[:user]) format.html { redirect_to(@user, :notice => 'User was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.xml def destroy @user = User.find(params[:id]) @user.destroy respond_to do |format| format.html { redirect_to(users_url) } format.xml { head :ok } end end def remoteget render :text => "text" end def reload puts '===> in RELOAD' + Time.now.to_s @user = User.find(session[:user_id]) puts 'user = ' + @user.user_name render :text => "text" end end
# Settings set :source, '..' set :css_dir, 'middleman/assets/stylesheets' set :js_dir, 'middleman/assets/javascripts' set :images_dir, 'middleman/assets/images' set :fonts_dir, 'middleman/assets/fonts' set :layouts_dir, 'middleman/layouts' set :data_dir, 'data' set :helpers_dir, 'helpers' ## Playbook settings set :playbook_chapter_belongs_to_section_key, :title set :playbook_section_has_many_chapters_key, :'playbook-section-chapters' # Ignored paths ignore '**/.keep' ignore '.github/**' ignore /^middleman(?!\/assets)(?!\/admin)(?!\/uploads).*/ ignore /^(?!.*\/.*)(?!index\.html).*/ # Activate and configure extensions # https://middlemanapp.com/advanced/configuration/#configuring-extensions activate :autoprefixer do |prefix| prefix.browsers = 'last 2 versions' end # Pretty urls activate :directory_indexes # Use Pry as the Middleman console activate :pry # Layouts # https://middlemanapp.com/basics/layouts/ # Per-page layout changes page '/*.xml', layout: false page '/*.json', layout: false page '/*.txt', layout: false # With alternative layout # page '/path/to/file.html', layout: 'other_layout' page '/', layout: 'home' page /.+\.html$/, layout: 'playbook/chapter' page '/middleman/admin/*', layout: false # Proxy pages # https://middlemanapp.com/advanced/dynamic-pages/ # proxy( # '/this-page-has-no-template.html', # '/template-file.html', # locals: { # which_fake_page: 'Rendering a fake page with a local variable' # }, # ) # Helpers # Methods defined in the helpers block are available in templates # https://middlemanapp.com/basics/helper-methods/ # helpers do # def some_helper # 'Helping' # end # end # Middleman fails to reload helpers, although it notices their modification # This force-reloads them. See # https://github.com/middleman/middleman/issues/1105#issuecomment-305715209 Dir['helpers/*.rb'].each(&method(:load)) # Code that doesn't belong to helpers # lib/**/*.rb is avoided in order to ensure namespaced files to be loaded before the namespace definition Dir['lib/*.rb', 'lib/*/*.rb'].each(&method(:load)) activate :playbook # Build-specific configuration # https://middlemanapp.com/advanced/configuration/#environment-specific-settings configure :build do activate :minify_css activate :minify_javascript # Append a hash to asset urls (make sure to use the url helpers) activate :asset_hash, ignore: %r{^middleman/assets/not-hashed/.*} # activate :asset_host, :host => '//YOURDOMAIN.cloudfront.net' end import_file File.expand_path('../_redirects', root), '/_redirects'
require 'test_helper' class UserTest < ActiveSupport::TestCase test "all components included" do assert User.create(name: "test", email: "test@test.com", fbid: "123456", wallet: 0).valid? assert_not User.create(name: "test", email: "test@test.com").valid? assert_not User.create(name: "test", wallet: 0).valid? assert_not User.create(email: "test@test.com", wallet: 0).valid? end test "unique email" do assert User.create(name: "Test", email: "test@test.com", fbid: "12345", wallet: 0).valid? assert_not User.create(name: "Test2", email: "test@test.com", fbid: "123456", wallet: 0).valid? end test "wallet non-negative" do assert_not User.create(name: "Test", email: "test@test.com", wallet: -1.0).valid? end test "average rating" do user1 = User.create(name: "test1", email: "test1@testemail.com", wallet: 10) user2 = User.create(name: "test2", email: "test2@testemail.com", wallet: 10) req1 = Request.create(title: "test", user: user1, amount: 100, lat: 100, longitude: 100, due: "2016-10-24 00:14:55") req2 = Request.create(title: "test2", user: user1, amount: 100, lat: 100, longitude: 100, due: "2016-10-24 00:14:55") rev1 = Review.create(reviewer: user1, reviewee: user2, request: req1, rating: 5) rev2 = Review.create(reviewer: user1, reviewee: user2, request: req2, rating: 4) assert_equal 4.5, user2.avgRating end test "average rating with no ratings" do user = User.create(name: "test1", email: "testnoreviews@testemail.com", wallet: 10) assert_equal 0.0, user.avgRating end test "login existing" do namey = users(:namey) user = User.login(namey.name, namey.email, namey.fbid) assert_equal namey.id, user.id end test "login new user" do name = 'Login New User Test User' email = 'loginnewusertestuser@example.com' fbid = '12345' # Ensure this is a new user's credentials User.all.each do |u| assert_not_equal name, u.name assert_not_equal email, u.email end user = User.login(name, email, fbid) assert_not_nil user # Ensure the new user got saved assert_equal User.find_by(id: user.id), user end end
Pod::Spec.new do |s| s.name = 'glomex' s.version = '1.0.0' s.summary = 'This pod can be user for a Glomex Content SDK' s.description = <<-DESC This pod can be user for a Glomex Content SDK. Please find the instruction on README DESC s.homepage = 'https://github.com/glomex/content-sdk-ios/' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'mrgerych@gmail.com' => 'mrgerych@gmail.com' } s.source = { :git => 'https://github.com/glomex/content-sdk-ios.git', :tag => s.version.to_s } s.ios.deployment_target = '8.0' s.default_subspec = 'Default' s.subspec 'Default' do |default| default.dependency 'glomex/content-sdk' end s.subspec 'content-sdk' do |contentsdk| contentsdk.source_files = 'Sources/**/*' end end
class User attr_accessor :balance, :cards, :name def initialize(desk) @desk = desk @balance = 100 @cards = [] end def add_card(card) @cards << card end def score @desk.score(@cards) end end
module QunitForRails class QunitTestsController < ApplicationController skip_before_filter :authorize layout "qunit_for_rails/main" def index test_files = [] Dir.glob(::Rails.root.to_s + "/public/javascripts/test/*").each { |file| if file.end_with?('_test.js') test_files << file.split('/').last end } render :index, :locals => { :test_files => test_files, :root_url => ENV['RAILS_RELATIVE_URL_ROOT'] } end end end
class CreateActors < ActiveRecord::Migration[4.2] def change create_table :actors do |n| n.string :first_name n.string :last_name end end end
class ApplicationController < ActionController::API include DeviseTokenAuth::Concerns::SetUserByToken include ActionController::MimeResponds include Pundit def pundit_user current_users_model end def skip_bullet previous_value = Bullet.enable? Bullet.enable = false yield ensure Bullet.enable = previous_value end rescue_from StandardError do |e| Rails.logger.error( e.message + "\n" + e.backtrace[0, 10].join("\n\t") ) if e.class == Pundit::NotAuthorizedError status = 401 error = e.message else status = :bad_request error = e.message end render json: { type: e.class, error: error }, status: status end end
class ApiController < ActionController::Base skip_before_action :verify_authenticity_token before_action :authentication_user_from_token! before_action :set_default_format def set_default_format request.format = :json end def authentication_user_from_token! if params[:auth_token].present? user = User.find_by(authenication_token: params[:auth_token]) sign_in(user, store: false) if user end end end
require 'fileutils' require 'hashie/mash' require 'proton' require 'wallarm/common/proton_file_info' require 'wallarm/common/sys_info' class NodeDataSyncer FORMATS = { 'proton.db' => Proton::DB_VERSION, 'lom' => Proton::LOM_VERSION } DEFAULTS = { enabled: true, key_file: '/etc/wallarm/license.key', protondb: '/etc/wallarm/proton.db', lom: '/etc/wallarm/lom', interval: 600, rand_delay: 300, timeout: 900, owner: 'root', group: 'wallarm', mode: 0640 } attr_accessor :api attr_reader :conf, :logger def initialize(args = {}) @api = args[:api] @logger = args[:logger] || Logger.new(nil) configure!(args[:opts] || {}) end def enabled? conf.enabled end def registered? !@api.nil? end def sync return true unless enabled? return false unless registered? pid = fork do logger.debug 'Syncnode started' if sync_no_fork exit 0 else exit 1 end end watchdog = Thread.new do sleep conf.timeout logger.warn 'Syncnode timeout reached' Process.kill 'TERM', pid sleep 5 Process.kill 'KILL', pid end _, rc = Process.wait2 pid watchdog.kill if rc.nil? logger.error 'Unknown syncnode exit code' return false end unless rc.success? logger.error "Syncnode exited with code #{rc.exitstatus}" if rc.exited? logger.error "Syncnode killed by signal #{rc.termsig}" if rc.signaled? return false end true end def sync_no_fork begin license = api.get('/v2/license') current = File.read(conf.key_file) rescue nil if license != current store(license, path: conf.key_file) logger.info 'License key was updated' else fix_file_permissions(path: conf.key_file) end rescue Wallarm::API2::Error => e logger.error "Can't fetch license key: #{e}" return false end rc = true begin if sync_file('proton.db', path: conf.protondb, owner: conf.owner, group: conf.group, mode: conf.mode) yield 'proton.db' if block_given? logger.info 'Proton.db was updated' else logger.debug 'Proton.db was not changed' end rescue => e rc = false logger.error "Can't sync proton.db: #{e}" end begin if sync_file('lom', path: conf.lom, owner: conf.owner, group: conf.group, mode: conf.mode) yield 'lom' if block_given? logger.info 'Lom was updated' else logger.debug 'Lom was not changed' end rescue => e rc = false logger.error "Can't sync lom: #{e}" end return rc end def sync_loop next_sync = 0 errors = 0 loop do time = Time.now.to_i unless enabled? && time > next_sync sleep 1 next end begin sync next_sync = time + conf.interval + rand(conf.rand_delay) errors = 0 logger.debug 'syncnode success!' rescue => e errors += 1 next_sync = time + 60 + rand(60) logger.error "#{errors} last syncs failed: #{e}" if errors % 10 == 1 end end end # returns: # true if file was changed # false if file was not changed # raise exception on error # def sync_file(type, args) file = args[:path] validate = args.fetch(:validate, true) fileinfo = ProtonFileInfo.new(conf.key_file, file, validate) data = fetch(type, fileinfo) if data.nil? fix_file_permissions(args) return false end tmpfile = File.join( File.dirname(file), ".#{File.basename(file)}.new") store(data, args.merge(:path => tmpfile)) data = nil GC.start if validate && !file_checker.check(tmpfile) raise "bad file, error message: `#{file_checker.error_msg}'" end File.rename( tmpfile, file) true ensure File.unlink tmpfile rescue nil end private def with_env(name) value = ENV[name] yield value if value end def with_bool_env(name) with_env(name) do |value| case value.downcase when 'true', 'yes', '1' yield true else yield false end end end def configure!(opts = {}) @conf = Hashie::Mash.new(DEFAULTS) conf.group = SysInfo.nginx_group unless SysInfo.nginx_group.nil? with_bool_env('WALLARM_SYNCNODE') { |v| conf.enabled = v } with_env('WALLARM_SYNCNODE_INTERVAL') { |v| conf.interval = v.to_i } with_env('WALLARM_SYNCNODE_RAND_DELAY') { |v| conf.rand_delay = v.to_i } with_env('WALLARM_SYNCNODE_TIMEOUT') { |v| conf.timeout = v.to_i } with_env('WALLARM_SYNCNODE_OWNER') { |v| conf.owner = v } with_env('WALLARM_SYNCNODE_GROUP') { |v| conf.group = v } with_env('WALLARM_SYNCNODE_MODE') { |v| conf.mode = v.to_i(8) } opts.delete_if{ |_,v| v.nil? } conf.merge! opts end def file_checker Proton::FileChecker.new(conf.key_file) end # returns: data, nil or exception def fetch(type, fileinfo) if fileinfo.type == type current = { :format => fileinfo.format, :version => fileinfo.version, :checksum => fileinfo.checksum } end api.node_data(type, FORMATS[type], current) end def store(data, args) File.open(args[:path], "wb") do |f| uid = args[:owner] || conf.owner uid = Etc.getpwnam( uid.to_s).uid unless Integer == uid gid = args[:group] || conf.group gid = Etc.getgrnam( gid.to_s).gid unless Integer == gid f.chown( uid, gid) f.chmod args[:mode] || conf.mode f.write data end end def fix_file_permissions(args) uid = args[:owner] || conf.owner uid = Etc.getpwnam( uid.to_s).uid unless Integer == uid gid = args[:group] || conf.group gid = Etc.getgrnam( gid.to_s).gid unless Integer == gid mode = args[:mode] || conf.mode File.chown( uid, gid, args[:path]) File.chmod( mode, args[:path]) end end
=begin This is assignment 21 and is due on Feb 05, 2015. Write a Person class and some code to use it, following the directions below. First Create a Person class with attributes: first name, last name, and birthdate. First name and last name should not be able to be written to, but should be readable. Birthdate can be set and read. Create a public instance method called name that takes the name and sets the first name and last name instance variables. This is so the first name and last name attributes are set by passing in one name. Create a public instance method called age to calculate and return the user's age. Now, outside the Person class, ask the user their information and use it to create the Person object. After asking each user their information, output the user's age. Next Create a class variable that will count the number of people that enter in their information. After you output the person's age, also output the number of person they are so far (using the class variable). Loop to allow another user to enter their information. (exit when user enters \q for name). Create a Person object for each user. Create a private method called calculateAge. This should contain the functionality you previously had in the age method. The public age method should now call this new private calculateAge method. =end #!/usr/bin/ruby # Requires some libraries. require 'date' require 'active_support' require 'active_support/all' # Defines setters/getters. class Person attr_reader :first_name attr_reader :last_name attr_accessor :birthdate @@count_user = 0 # Takes in full name, converts it to first and last. def name(full_name) name = full_name.split(' ') @first_name = name[0] @last_name = name[1] end # Figures out the user's age in years. def age # Uses a Private def below return calculateAge end # Increment the User count def initialize @@count_user += 1 end def self.number_of_users @@count_user end # Private def private def calculateAge (Date.today - @birthdate.to_date).to_i/365 end end
require 'spec_helper' require 'rose/active_record' module RoseActiveRecordSpecs class Person < ActiveRecord::Base attr_protected :password end class Admin < Person end class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post belongs_to :author, :class_name => "Person" end class Subject < ActiveRecord::Base has_many :tests end class Test < ActiveRecord::Base belongs_to :subject belongs_to :student, :class_name => "Person" end describe Rose, "ActiveRecord adapter" do before(:suite) do # ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/log/test.log") ActiveRecord::Migration.verbose = false ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") load(File.dirname(__FILE__) + "/../db/schema.rb") person_1 = Person.create(:name => "Person #1") person_2 = Person.create(:name => "Person #2") post_1 = Post.create(:title => "Post #1", :guid => "P1") post_1.comments.create(:author => person_1) post_1.comments.create(:author => person_2) post_2 = Post.create(:title => "Post #2", :guid => "P2") post_2.comments.create(:author => person_2) end describe "make report" do before do Post.rose(:post_comments) do rows do column("Post", &:title) column("Comments") { |item| item.comments.size } end end Post.rose(:post_comments_sorted_asc) do rows do column("Post", &:title) column("Comments") { |item| item.comments.size } end sort("Comments", :ascending) end Post.rose(:post_comments_sorted_desc) do rows do column("Post", &:title) column("Comments") { |item| item.comments.size } end sort("Comments", :descending) end end it "should report on posts' comments" do Post.rose_for(:post_comments).should match_table <<-eo_table.gsub(%r{^ }, '') +--------------------+ | Post | Comments | +--------------------+ | Post #1 | 2 | | Post #2 | 1 | +--------------------+ eo_table end it "should order by comments size" do Post.rose_for(:post_comments_sorted_asc).should match_table <<-eo_table.gsub(%r{^ }, '') +--------------------+ | Post | Comments | +--------------------+ | Post #2 | 1 | | Post #1 | 2 | +--------------------+ eo_table Post.rose_for(:post_comments_sorted_desc).should match_table <<-eo_table.gsub(%r{^ }, '') +--------------------+ | Post | Comments | +--------------------+ | Post #1 | 2 | | Post #2 | 1 | +--------------------+ eo_table end it "should report only posts with #2" do Post.rose_for(:post_comments, :conditions => ["title like ?", "%#2%"]).should match_table <<-eo_table.gsub(%r{^ }, '') +--------------------+ | Post | Comments | +--------------------+ | Post #2 | 1 | +--------------------+ eo_table end end describe "make report with sigma" do before do Comment.rose(:author_comments) do rows do column("Author") { |item| item.author.name } column("Posts") { |item| item.post.title } column("Comments") { |item| true } end summary("Author") do column("Posts") { |posts| posts.join(", ") } column("Comments") { |comments| comments.size } end end end it "should get authors and their comments" do Comment.rose_for(:author_comments).should match_table <<-eo_table.gsub(%r{^ }, '') +-----------------------------------------+ | Author | Posts | Comments | +-----------------------------------------+ | Person #1 | Post #1 | 1 | | Person #2 | Post #1, Post #2 | 2 | +-----------------------------------------+ eo_table end end describe "make report with pivot" do it "should make report with pivot" do elisa = Person.create(:name => "Elisa") mary = Person.create(:name => "Mary") english = Subject.create(:name => "English") math = Subject.create(:name => "Math") science = Subject.create(:name => "Science") art = Subject.create(:name => "Art") history = Subject.create(:name => "History") french = Subject.create(:name => "French") Test.create(:student => elisa, :subject => english, :score => 87, :created_at => Date.parse('January 2010')) Test.create(:student => elisa, :subject => math, :score => 65, :created_at => Date.parse('January 2010')) Test.create(:student => elisa, :subject => science, :score => 58, :created_at => Date.parse('January 2010')) Test.create(:student => elisa, :subject => art, :score => 89, :created_at => Date.parse('January 2010')) Test.create(:student => elisa, :subject => history, :score => 81, :created_at => Date.parse('January 2010')) Test.create(:student => elisa, :subject => french, :score => 62, :created_at => Date.parse('January 2010')) Test.create(:student => elisa, :subject => english, :score => 51, :created_at => Date.parse('February 2010')) Test.create(:student => elisa, :subject => math, :score => 72, :created_at => Date.parse('February 2010')) Test.create(:student => elisa, :subject => science, :score => 89, :created_at => Date.parse('February 2010')) Test.create(:student => elisa, :subject => art, :score => 83, :created_at => Date.parse('February 2010')) Test.create(:student => elisa, :subject => history, :score => 84, :created_at => Date.parse('February 2010')) Test.create(:student => elisa, :subject => french, :score => 57, :created_at => Date.parse('February 2010')) Test.create(:student => elisa, :subject => english, :score => 41, :created_at => Date.parse('March 2010')) Test.create(:student => elisa, :subject => math, :score => 71, :created_at => Date.parse('March 2010')) Test.create(:student => elisa, :subject => science, :score => 41, :created_at => Date.parse('March 2010')) Test.create(:student => elisa, :subject => art, :score => 92, :created_at => Date.parse('March 2010')) Test.create(:student => elisa, :subject => history, :score => 91, :created_at => Date.parse('March 2010')) Test.create(:student => elisa, :subject => french, :score => 56, :created_at => Date.parse('March 2010')) Test.create(:student => mary, :subject => english, :score => 87, :created_at => Date.parse('January 2010')) Test.create(:student => mary, :subject => math, :score => 53, :created_at => Date.parse('January 2010')) Test.create(:student => mary, :subject => science, :score => 35, :created_at => Date.parse('January 2010')) Test.create(:student => mary, :subject => art, :score => 61, :created_at => Date.parse('January 2010')) Test.create(:student => mary, :subject => history, :score => 58, :created_at => Date.parse('January 2010')) Test.create(:student => mary, :subject => french, :score => 92, :created_at => Date.parse('January 2010')) Test.create(:student => mary, :subject => english, :score => 68, :created_at => Date.parse('February 2010')) Test.create(:student => mary, :subject => math, :score => 54, :created_at => Date.parse('February 2010')) Test.create(:student => mary, :subject => science, :score => 56, :created_at => Date.parse('February 2010')) Test.create(:student => mary, :subject => art, :score => 59, :created_at => Date.parse('February 2010')) Test.create(:student => mary, :subject => history, :score => 61, :created_at => Date.parse('February 2010')) Test.create(:student => mary, :subject => french, :score => 93, :created_at => Date.parse('February 2010')) Test.create(:student => mary, :subject => english, :score => 41, :created_at => Date.parse('March 2010')) Test.create(:student => mary, :subject => math, :score => 35, :created_at => Date.parse('March 2010')) Test.create(:student => mary, :subject => science, :score => 41, :created_at => Date.parse('March 2010')) Test.create(:student => mary, :subject => art, :score => 48, :created_at => Date.parse('March 2010')) Test.create(:student => mary, :subject => history, :score => 67, :created_at => Date.parse('March 2010')) Test.create(:student => mary, :subject => french, :score => 90, :created_at => Date.parse('March 2010')) Test.rose(:scores) do rows do column("Month") { |test| I18n.l(test.created_at, :format => :short) } column("Subject") { |test| test.subject.name } column("Student") { |test| test.student.name } column(:score => "Score") end pivot("Month", "Subject") do |matching_rows| matching_rows.map(&:Score).map(&:to_f).sum end end Test.rose_for(:scores).should match_table <<-eo_table.gsub(%r{^ }, '') +---------------------------------------------------------------------+ | Month | Art | Science | English | French | Math | History | +---------------------------------------------------------------------+ | 01 Jan 00:00 | 150.0 | 93.0 | 174.0 | 154.0 | 118.0 | 139.0 | | 01 Feb 00:00 | 142.0 | 145.0 | 119.0 | 150.0 | 126.0 | 145.0 | | 01 Mar 00:00 | 140.0 | 82.0 | 82.0 | 146.0 | 106.0 | 158.0 | +---------------------------------------------------------------------+ eo_table end end describe "run report" do before do Comment.rose(:author_comments) do rows do column("Author") { |item| item.author.name } column("Posts") { |item| item.post.title } column("Comments") { |item| item.destroy } end end end it "should run report within transaction" do all_sizes = lambda { [Person.count, Post.count, Comment.count] } lambda { Comment.rose_for(:author_comments) }.should_not change(all_sizes, :call) end end describe "import report" do before do Post.rose(:with_update) { rows do identity(:guid => "ID") column("Title", &:title) column("Comments") { |item| item.comments.size } end sort("Comments", :descending) roots do find do |items, idy| items.find { |item| item.guid == idy } end update do |record, updates| record.update_attribute(:title, updates["Title"]) end end } @post_3 = Post.create(:title => "Post #3", :guid => "P3") @post_4 = Post.create(:title => "Post #4", :guid => "P4") end after do @post_3.destroy; @post_4.destroy end it "should update report" do Post.root_for(:with_update, { :with => { "P3" => { "Title" => "Third Post", "something" => "else" }, "P4" => { "Title" => "Fourth Post" } } }).should match_table <<-eo_table.gsub(%r{^ }, '') +-----------------------------+ | ID | Title | Comments | +-----------------------------+ | P1 | Post #1 | 2 | | P2 | Post #2 | 1 | | P4 | Fourth Post | 0 | | P3 | Third Post | 0 | +-----------------------------+ eo_table Post.all.map(&:title).should == ["Post #1", "Post #2", "Third Post", "Fourth Post"] end it "should update report with conditions" do Post.root_for(:with_update, { :with => { "P3" => { "Title" => "Third Post", "something" => "else" }, "P4" => { "Title" => "Fourth Post" } } }, { :conditions => ["title like ?", "%#3%"] }).should match_table <<-eo_table.gsub(%r{^ }, '') +----------------------------+ | ID | Title | Comments | +----------------------------+ | P3 | Third Post | 0 | +----------------------------+ eo_table Post.all.map(&:title).should == ["Post #1", "Post #2", "Third Post", "Post #4"] end it "should update report from CSV" do Post.root_for(:with_update, { :with => "spec/examples/update_posts.csv" }).should match_table <<-eo_table.gsub(%r{^ }, '') +-----------------------------+ | ID | Title | Comments | +-----------------------------+ | P1 | Post #1 | 2 | | P2 | Post #2 | 1 | | P4 | Fourth Post | 0 | | P3 | Third Post | 0 | +-----------------------------+ eo_table Post.all.map(&:title).should == ["Post #1", "Post #2", "Third Post", "Fourth Post"] end end describe "preview import report" do before do Post.rose(:for_import) { rows do identity(:guid => "ID") column("Title", &:title) column("Comments") { |item| item.comments.size } end sort("Comments", :descending) roots do find do |items, idy| items.find { |item| item.guid == idy } end preview_update do |record, updates| record.title = updates["Title"] end update { raise Exception, "not me!" } end } end it "should preview changes" do Post.root_for(:for_import, { :with => { "P1" => { "Title" => "First Post", "something" => "else" }, "P2" => { "Title" => "Second Post" } }, :preview => true }).should match_table <<-eo_table.gsub(%r{^ }, '') +-----------------------------+ | ID | Title | Comments | +-----------------------------+ | P1 | First Post | 2 | | P2 | Second Post | 1 | +-----------------------------+ eo_table Post.all.map(&:title).should == ["Post #1", "Post #2"] end end describe "create import report" do before do Post.rose(:for_create) { rows do identity(:guid => "ID") column("Title", &:title) column("Comments") { |item| item.comments.size } end sort("Comments", :descending) roots do find do |items, idy| items.find { |item| item.guid == idy } end preview_create do |idy, updates| post = Post.new(:guid => idy) post.title = updates["Title"] post end create do |idy, updates| post = create_previewer.call(idy, updates) post.save! post end end } end it "should preview create" do Post.root_for(:for_create, { :with => { "P3" => { "Title" => "Post #3" } }, :preview => true }).should match_table <<-eo_table.gsub(%r{^ }, '') +-------------------------+ | ID | Title | Comments | +-------------------------+ | P1 | Post #1 | 2 | | P2 | Post #2 | 1 | | P3 | Post #3 | 0 | +-------------------------+ eo_table end it "should create" do Post.root_for(:for_create, { :with => { "P3" => { "Title" => "Post #3" } } }).should match_table <<-eo_table.gsub(%r{^ }, '') +-------------------------+ | ID | Title | Comments | +-------------------------+ | P1 | Post #1 | 2 | | P2 | Post #2 | 1 | | P3 | Post #3 | 0 | +-------------------------+ eo_table Post.last.title.should == "Post #3" Post.last.destroy end end end end
# frozen_string_literal: true require 'rails_helper' describe 'Servers index table', type: :feature do it 'displays server information' do create(:server_index) visit servers_path expect(body).to have_text('server-dev') expect(body).to have_text('123.45.67.890') expect(body).to have_text('pupgraded') end it 'displays a link when server belongs to a deploy environment' do create(:repo_with_servers) visit servers_path expect(body).to have_link('server-prod-b', href: '/repositories/Hello-World') end it 'gets correct results from true filter' do create(:server_index) visit servers_path find('#pupgraded').select('true') click_button 'Filter' expect(body).to have_text('server-dev') end it 'gets correct results from false filter' do create(:server_index) visit servers_path find('#pupgraded').select('false') click_button 'Filter' expect(body).not_to have_text('server-dev') end end
class Person attr_accessor :name def initialize(name) @name = name end def greeting "Hello #{name}" end end person = Person.new person.name = "Dennis" puts person.greeting
name 'adminscripts' maintainer 'Boye Holden' maintainer_email 'boye.holden@hist.no' license 'Apache 2.0' description 'Collection of useful adminscripts we want to deploy' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.2.0' recipe 'adminscripts::lowdisk', 'Creates a script that sends an warning if low disk space' %w(ubuntu debian).each do |os| supports os end %w(postfix).each do |pkg| suggests pkg end %w(cron).each do |pkg| depends pkg end
class ProjectSerializer < ActiveModel::Serializer attributes :id, :name, :description has_many :issues, embed: :ids end
# class to build a person object class Person attr_accessor :name attr_reader :age @@people = [] def initialize(initial_name, initial_age) @name = initial_name @age = initial_age @@people.push(self) end def say_name puts 'Hi, my name is ' + @name + '.' end def say_age puts "I am #{@age} years old." end def self.get_people @@people end end # Inheritance is indicated using the `<` symbol after the child class' name. class LoudPerson < Person # LoudPerson's `say_name` overrides that of the `Person` class. def say_name puts "HEY YOU, MY NAME IS #{@name.upcase}!" end end jill = Person.new('Jill', 10) bob = LoudPerson.new('Bob', 20) # Both `say_age` methods produce the same result because it was not overwritten in the `LoudPerson` class. jill.say_age # => "I am 10 years old." bob.say_age # => "I am 20 years old." # The `say_name` methods produce different results because the original was overwritten in the `LoudPerson` class. jill.say_name # => "My name is Jill." bob.say_name # => "HEY YOU, MY NAME IS BOB!"
class CommentsController < ApplicationController load_and_authorize_resource before_action :load_product, only: :update def create @comment = current_user.comments.build comment_params @product = @comment.product if @comment.save respond_to do |format| format.js end else flash[:danger] = t "comment_not_create" redirect_to request.referrer end end def edit end def update if @comment.update_attributes comment_params flash[:success] = t "comment_update" else flash[:danger] = t "comment_not_update" end redirect_to product_path @product.id end def destroy if @comment.destroy flash[:success] = t "del_complete" else flash[:danger] = t "comment_not_delete" end redirect_to request.referrer end private def comment_params params.require(:comment).permit :content, :product_id end def load_product @product = Product.find_by id: @comment.product_id unless @product flash[:danger] = t "product_not_found" redirect_to request.referrer end end end
class TicketsController < ApplicationController before_action :current_board def new end def create title = params[:ticket][:title] description = params[:ticket][:description] status = params[:ticket][:status] ticket = current_board.tickets.new(title: title,description: description, status: status.to_i) # ticket = Ticket.new(ticket_params) if ticket.save redirect_to board_path(current_board) else flash[:error] = "something went wrong" redirect_to board_path(current_board) end end def update ticket = Ticket.find_by(id: params[:id]) status = params[:status] status_number = Ticket.statuses[status].to_i + 1 ticket.update_attributes(status: status_number) redirect_to board_path(current_board) end def current_board @board = Board.find_by(id: params[:board_id]) end private def ticket_params params.require(:ticket).permit(:title, :description, :status) end end
class Achievement < ApplicationRecord belongs_to :user validates :name, presence: true validates :majors, presence: true validates :organization, presence: true validates :received_time, presence: true end
require "rspec" require "haversine" require "pry" module Locatable def distance_to lat, long first_station = Station.new(lat,long) distance = Haversine.distance(self.latitude, self.longitude, lat, long) distance.to_miles end def Locatable.included other other.extend Locatable::ClassMethods end module ClassMethods def closest_to lat, long, count = nil distances = {} self.all.each do |i| distances[i] = (Haversine.distance(i.latitude, i.longitude, lat, long)).to_miles end distances = distances.sort_by{ |k, v| v } if count == nil return distances.first.first else distances = distances.first(2) distances = distances.map {|object, distance| object} return distances end end end end class Station attr_reader :latitude, :longitude include Locatable def initialize lat, long @latitude, @longitude = lat, long end def self.all [ Station.new(12, -36), Station.new(10, -33), Station.new(77, 45) ] end end describe Locatable do it "can find distances" do s = Station.new 10, -33 expect(s.distance_to 10, -33).to eq 0 expect(s.distance_to 10, -34).to be < 10000 # ?? end it "can find closest stations" do s = Station.closest_to 10, -34 expect(s.latitude ).to eq 10 expect(s.longitude).to eq -33 end it "can find list of closest" do s = Station.closest_to 10, -34, count: 2 expect(s.count).to eq 2 expect(s.last.latitude).to eq 12 end end
module CommissionsHelper COMMISSION_RATE = '.04'.to_f BREAKAGE_RATE = '1.18'.to_f # leave at 1 if no amount is deducted from commission def positive_adjustment_commission(event) additional_charges = event.additional_charges.nil? ? 0 : event.additional_charges comm = ((additional_charges + ((event.amount_of_guests - event.minimum_guarantee) * event.base_price)) * COMMISSION_RATE) / BREAKAGE_RATE comm.round(2) end def new_party_commission(event) comm = (event.minimum_guarantee * event.base_price) * COMMISSION_RATE / BREAKAGE_RATE comm.round(2) end def compute_commission_on_all(new_events, month_events) amount = 0 new_events.each { |event| amount += new_party_commission(event) } month_events.each { |event| amount += positive_adjustment_commission(event) } amount end end
cask "tm-asciidoc" do version "0.2" sha256 "d099f2a92667cb8de9233e951181199ec40e542608d33ecd552ea790bda1a8ac" url "https://github.com/mattneub/AsciiDoc-TextMate-2.tmbundle/archive/v#{version}.tar.gz" name "AsciiDoc bundle for TextMate 2" homepage "https://github.com/mattneub/AsciiDoc-TextMate-2.tmbundle" tmbundle "AsciiDoc-TextMate-2.tmbundle-#{version}", target: "AsciiDoc-TextMate-2.tmbundle" end
# # Make assets # namespace :grunt do task :build do on roles(:app), in: :sequence, wait: 5 do within fetch(:assets_path, release_path) do execute :grunt, fetch(:grunt_build) end end end end
MRuby::Gem::Specification.new('mruby-require') do |spec| spec.licenses = ["MIT"] spec.authors = ["Nathan Ladd"] spec.summary = "require, require_relative, load backfill" spec.homepage = "https://github.com/test-bench/mruby-ruby-compat" spec.bins = ['mruby-require'] end
# frozen_string_literal: true require './frame' class Game def initialize(game_score) all_score = take_in_game(game_score) sepalated_score = separate_game_to_frame(all_score) @frames = sepalated_score.map { |s| Frame.new(*s) } end def score after_adjustment = @frames.map.with_index do |frame, i| if frame.spare? sum_spare_score(frame, @frames[i + 1]) elsif frame.strike? sum_strike_score(frame, @frames[i + 1], @frames[i + 2]) else frame.score end end puts after_adjustment.sum end private def take_in_game(game_score) game_score.split(',').map { |x| x == 'X' ? 'X' : x.to_i } end def separate_game_to_frame(game_score) frames = [] frame = [] game_score.each do |s| frame << s # 2shot目もframeに入れて欲しい場合nextで2投目処理へnextする。 # frameが2shot入っていなくストライクではないとき、もしくは10フレーム目はここで処理をループさせる next if frame.length != 2 && s != 'X' || frames.length > 9 frames << frame # frames.lengthが9の時のframesに10フレーム目が入った時点で10フレーム目の2投目を入れる為に処理をnextする。 next if frames.length == 10 frame = [] end frames end def sum_spare_score(frame, next_frame) frame.score + next_frame&.first_shot&.score.to_i end def sum_strike_score(frame, next_frame = nil, after_next_frame = nil) # ラストフレームの処理 if @frames[-1] == frame frame.score # 9フレーム目もしくは、次フレームがストライクではない時の処理 elsif @frames[-2] == frame || !next_frame.strike? frame.score + next_frame.first_shot.score + next_frame.second_shot.score # 次フレームがストライクの時の処理(elsifで分岐することで明示的に次フレームがストライクの処理を表す) elsif next_frame.strike? frame.score + next_frame.first_shot.score + after_next_frame.first_shot.score end end end game = Game.new(ARGV[0]) game.score
require 'rspec/core' describe 'permit_actions matcher' do context 'no actions are specified' do before do class PermitActionsTestPolicy1 end end subject { PermitActionsTestPolicy1.new } it { is_expected.not_to permit_actions([]) } end context 'one action is specified' do before do class PermitActionsTestPolicy2 end end subject { PermitActionsTestPolicy2.new } it { is_expected.not_to permit_actions([:test]) } end context 'more than one action is specified' do context 'test1? and test2? are permitted' do before do class PermitActionsTestPolicy3 def test1? true end def test2? true end end end subject { PermitActionsTestPolicy3.new } it { is_expected.to permit_actions([:test1, :test2]) } end context 'test1? is permitted, test2? is forbidden' do before do class PermitActionsTestPolicy4 def test1? true end def test2? false end end end subject { PermitActionsTestPolicy4.new } it { is_expected.not_to permit_actions([:test1, :test2]) } end context 'test1? is forbidden, test2? is permitted' do before do class PermitActionsTestPolicy5 def test1? false end def test2? true end end end subject { PermitActionsTestPolicy5.new } it { is_expected.not_to permit_actions([:test1, :test2]) } end context 'test1? and test2? are both forbidden' do before do class PermitActionsTestPolicy6 def test1? false end def test2? false end end end subject { PermitActionsTestPolicy6.new } it { is_expected.not_to permit_actions([:test1, :test2]) } end end end
require 'rails_helper' describe LineItem do it "has a valid factory" do expect(build(:line_item)).to be_valid end it "can calculate total price per line item" do food = create(:food, price:15000) line_item = create(:line_item, food: food, quantity:2) expect(line_item.total_price).to eq(30000) end # it "doesn't add food with different restaurant" do # cart = create(:cart) # restaurant1 = create(:restaurant) # food1 = create(:food, restaurant: restaurant1) # restaurant2 = create(:restaurant) # food2 = create(:food, restaurant: restaurant2) # line_item1 = create(:line_item, food: food1, cart: cart) # line_item2= build(:line_item, food: food2, cart: cart) # line_item2.valid? # #expect(line_item2.errors[:base]).to include("can't add food from different restaurant") # expect{ line_item2.save }.not_to change(LineItem, :count) # end end describe Cart do it "has a valid factory" do expect(build(:cart)).to be_valid end it "can calculate total cart price" do cart = create(:cart) food1 = create(:food, price:10000) food2 = create(:food, price:15000) line_item1 = create(:line_item, cart: cart, food: food1, quantity:2) line_item2 = create(:line_item, cart: cart, food: food2, quantity:2) expect(cart.total_price).to eq(50000) end it "deletes line_items when deleted" do cart = create(:cart) food1 = create(:food) food2 = create(:food) line_item1 = create(:line_item, cart: cart, food: food1) line_item2 = create(:line_item, cart: cart, food: food2) cart.line_items << line_item1 cart.line_items << line_item2 expect { cart.destroy }.to change { LineItem.count }.by(-2) end end
class Tagging < ActiveRecord::Base attr_accessible :taggable_id, :taggable_type belongs_to :tag belongs_to :taggable, :polymorphic => true def caption self.taggable_type.constantize.find(self.taggable_id).caption end def id self.taggable_type.constantize.find(self.taggable_id).id end def namespace "#{taggable_type.downcase}" + 's' end def tags self.taggable_type.constantize.find(self.taggable_id).tags end def title self.taggable_type.constantize.find(self.taggable_id).title end end
json.array!(@text_book_exams) do |text_book_exam| json.extract! text_book_exam, :id, :text_book_id, :student_id, :point, :exam_date json.url text_book_exam_url(text_book_exam, format: :json) end
FactoryGirl.define do factory :todo_list do sequence(:name) { |n| "List #{n}" } end factory :todo_item do name { Faker::Company.bs } description { Faker::Lorem.paragraph(rand 5) } priority 0 end end
# Copyright (c) 2016, Regents of the University of Michigan. # All rights reserved. See LICENSE.txt for details. # The Umlaut service for ThreeSixtyLink class ThreeSixtyLink < Service required_config_params :base_url attr_reader :base_url # Call super at the end of configuring defaults def initialize(config) @display_name = '360 Link Resolver' @display_text = 'Get Full Text via 360 Link' @http_open_timeout = 3 @http_read_timeout = 5 @credits = { 'SerialsSolutions' => 'http://www.serialssolutions.com/en/services/360-link' } # Call super to get @base_url, @open_timeout, and @read_timeout super @client = UmlautThreeSixtyLink::Client::Agent.new( @base_url, @open_timeout, @read_timeout ) end # Returns an array of strings. # Used by auto background updater. def service_types_generated [ ServiceTypeValue['fulltext'], ServiceTypeValue['holding'], ServiceTypeValue['highlighted_link'], ServiceTypeValue['disambiguation'], ServiceTypeValue['site_message'] ] end def handle(request) records = @client.handle(request) ActiveRecord::Base.connection_pool.with_connection do records.enhance_metadata(request) end status = records.add_service(request, self) request.dispatched(self, status) end end
require 'test_helper' class SiteLayoutTest < ActionDispatch::IntegrationTest test "test presence of site links" do login_user get '/' assert_template 'thoughts/index' assert_template layout: 'layouts/application' assert_select "a[href=?]", root_path, count: 2 assert_select "a[href=?]", my_network_show_path assert_select "a[href=?]", destroy_user_session_path assert_select "a[href=?]", profiles_show_path(:id => @david.id) end #log in a devise user def login_user get user_session_path assert_equal 200, status @david = User.create(first_name: "David", last_name: "Smith", email: "david@mail.com", password: Devise::Encryptor.digest(User, "helloworld")) post user_session_path, 'user[email]' => @david.email, 'user[password]' => @david.password follow_redirect! end end
class CentroContratoDetalle < ActiveRecord::Base attr_accessible :id, :centro_contrato_id, :dia_id scope :ordenado_id, -> {order("id")} scope :ordenado_id_desc, -> {order("id desc")} belongs_to :centro_contrato belongs_to :dia end
module ValidateZipcode class Validator def initialize(zipcode, locale) @zipcode = zipcode variables(locale) unless @zipcode.blank? end def valid? return true if @zipcode.blank? @match end private def variables(locale) @match = regex_zipcode(locale.upcase) end def regex_zipcode(locale) if ValidateZipcode::Regex.respond_to?(locale) return ValidateZipcode::Regex.send(locale, @zipcode) end true end end end
class User < ActiveRecord::Base validates :name, :lastname, {presence: true, length: {minimum: 2, maximum: 20}} validates :password, :password_confirmation, {presence: true, length: {minimum: 6, maximum: 20}} has_secure_password end
class RbbtGraph attr_accessor :knowledge_base, :entities, :aesthetics, :associations, :rules def initialize @entities = {} @aesthetics = {} @associations = {} @rules = {} end def add_associations(associations, type = :edge) @associations[type] ||= [] @associations[type].concat associations.collect{|i| i } @associations[type].uniq! if AssociationItem === associations add_entities associations.target, associations.target_entity_type add_entities associations.source, associations.source_entity_type end end def add_entities(entities, type = nil, entity_options = {}) type = entities.base_entity.to_s if type.nil? and AnnotatedArray === entities raise "No type specified and entities are not Annotated, so could not guess" if type.nil? if knowledge_base good_entities = knowledge_base.translate(entities, type).compact.uniq else good_entities = entities end @namespace ||= entities.organism if entities.respond_to? :organism if @entities[type].nil? @entities[type] = good_entities else @entities[type].concat good_entities end end def add_aesthetic(elem, info) @aesthetics[elem] ||= [] @aesthetics[elem] << info end def add_rule(elem, info) @rules[elem] ||= [] @rules[elem] << info end def js_model js_model = {:entities => {}, :associations => {}, :aes_rules => {}, :edge_aes_rules => {}, :rules => {}, :edge_rules => {}} @entities.each do |type, codes| info = codes.info if codes.respond_to? :info info ||= {} js_model[:entities][type] = {:codes => codes, :entity_type => type, :info => info} end @associations.each do |type, codes| info = codes.info if codes.respond_to? :info info ||= {} js_model[:associations][type] = {:codes => codes, :database => type, :info => info} end @aesthetics.each do |type, info| aes_rule_type = (type == :node ? :aes_rules : :edge_aes_rules) js_model[aes_rule_type] = info end @rules.each do |type, info| rule_type = (type == :node ? :rules : :edge_rules) js_model[rule_type] = info end js_model end end
require 'spec_helper' describe GraphQLIncludable::Includes do subject { described_class.new(nil) } describe '#dig' do it 'digs' do a = subject.add_child(:a) b = subject.add_child(:b) a.add_child(:a_2).add_child(:a_3) b.add_child(:b_2) expect(subject.dig).to eq(subject.included_children) expect(subject.dig([])).to eq(subject.included_children) expect(subject.dig(:a, :a_2).included_children.length).to eq(1) expect(subject.dig(:a, :a_2).included_children[:a_3]).not_to be_nil expect(subject.dig([:a, :a_2]).included_children.length).to eq(1) expect(subject.dig([:a, :a_2]).included_children[:a_3]).not_to be_nil end end describe '#active_record_includes' do context 'when empty' do it 'returns no includes' do expect(subject.active_record_includes).to eq({}) end end context 'with 1 included key' do it 'returns an array with 1 key' do subject.add_child(:a) expect(subject.active_record_includes).to eq([:a]) end end context 'with multiple sibling keys' do it 'returns an array with 3 keys' do subject.add_child(:a) subject.add_child(:b) subject.add_child(:c) expect(subject.active_record_includes).to eq([:a, :b, :c]) end end context 'with nested included keys' do it 'returns a compatible Active Record shape' do subject.add_child(:a) nested_b = subject.add_child(:b) nested_b.add_child(:b_2) nested_c = subject.add_child(:c) nested_c.add_child(:c_1) nested_c2 = nested_c.add_child(:c_2) nested_c2.add_child(:c_2_1) nested_c2.add_child(:c_2_2) expect(subject.active_record_includes).to eq([:a, { b: [:b_2], c: [:c_1, { c_2: [:c_2_1, :c_2_2] }] }]) end end end describe '#merge_includes' do let(:other) { described_class.new(nil) } context 'simple merge' do it 'merges other into subject' do other.add_child(:test1) subject.add_child(:test2).add_child(:test3) subject.merge_includes(other) expect(subject.included_children.length).to eq(2) expect(subject.included_children.key?(:test1)).to eq(true) expect(subject.included_children.key?(:test2)).to eq(true) test2 = subject.included_children[:test2] expect(test2.included_children.length).to eq(1) expect(test2.included_children.key?(:test3)).to eq(true) end end context 'complex merge' do it 'merges other into subject' do other.add_child(:test1) subject.add_child(:test1).add_child(:test2) subject.merge_includes(other) expect(subject.included_children.length).to eq(1) expect(subject.included_children.key?(:test1)).to eq(true) test1 = subject.included_children[:test1] expect(test1.included_children.length).to eq(1) expect(test1.included_children.key?(:test2)).to eq(true) expect(other.included_children.length).to eq(1) expect(other.included_children.key?(:test1)).to eq(true) other_test1 = other.included_children[:test1] expect(other_test1.included_children.length).to eq(0) end it 'merges subject into other' do other.add_child(:test1) subject.add_child(:test1).add_child(:test2) other.merge_includes(subject) expect(subject.included_children.length).to eq(1) expect(subject.included_children.key?(:test1)).to eq(true) test1 = subject.included_children[:test1] expect(test1.included_children.length).to eq(1) expect(test1.included_children.key?(:test2)).to eq(true) expect(other.included_children.length).to eq(1) expect(other.included_children.key?(:test1)).to eq(true) other_test1 = other.included_children[:test1] expect(other_test1.included_children.length).to eq(1) expect(other_test1.included_children.key?(:test2)).to eq(true) end context 'appending to merged children references' do it 'does not keep in sync still' do subject_test2 = subject.add_child(:test1).add_child(:test2) other_test2 = other.add_child(:test1).add_child(:test2) test3 = other_test2.add_child(:test3) subject.merge_includes(other) subject_test2.add_child(:subject) other_test2.add_child(:other) expect(subject.active_record_includes).to eq(test1: { test2: [:test3, :subject] }) expect(other.active_record_includes).to eq(test1: { test2: [:test3, :other] }) test3.add_child(:test4) expect(subject.active_record_includes).to eq(test1: { test2: [:subject, { test3: [:test4] }] }) expect(other.active_record_includes).to eq(test1: { test2: [:other, { test3: [:test4] }] }) end end end end end
require_relative 'retrier' module Ehonda module Middleware module Server module ActiveRecord class Transaction RETRIER_OPTIONS = %i(tries sleep on_retriable_error) TRANSACTION_OPTIONS = %i(requires_new joinable isolation) def initialize options = {} @transaction_options = options.select { |k, _| TRANSACTION_OPTIONS.include? k } @retrier_default_options = options.select { |k, _| RETRIER_OPTIONS.include? k } end def call worker, _queue, _sqs_msg, _body Retrier.new(retrier_options(worker)).call do ::ActiveRecord::Base.transaction(@transaction_options) do yield end end end private def retrier_options worker options = @retrier_default_options.dup on_error = options.delete :on_retriable_error unless on_error.to_s.empty? begin callback_method = worker.method on_error rescue NameError raise "Worker #{worker.class} is using middleware "\ "#{self.class} which expected to find a callback "\ "method called '#{on_error}', but none was found." end options[:exception_cb] = callback_method end options end end end end end end
module ToDoApp module Controllers module Home include ToDoApp::Controller action 'Index' do include Lotus::Action::Session expose :tasks expose :user def call(params) user_id = session[:user] puts "SESSION: #{user_id}" if params[:newest] @tasks = ToDoApp::Repositories::TaskRepository.latest_tasks(user_id) elsif params[:alphabetically] @tasks = ToDoApp::Repositories::TaskRepository.alphabetically(user_id) else @tasks = ToDoApp::Repositories::TaskRepository.for_user(user_id) end @user = ToDoApp::Repositories::UserRepository.by_id(session[:user]) end end action "Create" do include Lotus::Action::Session def call(params) new_task = ToDoApp::Models::Task.new({ name: params[:task], user_id: session[:user] }) if !new_task.name.nil? && !new_task.name.strip.empty? ToDoApp::Repositories::TaskRepository.create(new_task) end redirect_to "/" end end #CRUD #Create Read Update Delete #Seperation of Concerns action 'Delete' do def call(params) task = ToDoApp::Repositories::TaskRepository.find(params[:task_id]) ToDoApp::Repositories::TaskRepository.delete(task) redirect_to '/' #lotusmethode end end end end end
class User < ApplicationRecord # 各フォームに値が入っているか確認 validates :name, presence: { message: "%{value} を入力してください" } validates :email, presence: { message: "%{value} を入力してください" } validates :password, presence: { message: "%{value} を入力してください" } #名前の文字数制限 validates :name, length: { maximum: 15,message: "は15字以内にしてください" } #メールの形式に関する制限 validates :email, format: { with: /[A-Za-z0-9._+]+@[A-Za-z]+.[A-Za-z]/, message: "は~ @ ~ . ~の表現にしてください" } #パスワードの文字数制限 validates :password, length: { in: 8..32, too_long:"は32文字以内にしてください", too_short:"は8文字以上にしてください"} validates :password, format: { with: /(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)/, message: "%{value}はアルファべット(大小)と半角数字の混合にしてください" } #パスワードが一致しているかの確認 # validates :password, confirmation: true validates :password, confirmation: { message: "とpasswordの値が一致していません" } # validates :password_confirmation, presence: true has_secure_password #画像テーブル has_many :topics # お気に入りテーブル has_many :favorites has_many :favorite_topics, through: :favorites, source: "topic" # コメントテーブル has_many :comments end
class CreateWardProfiles < ActiveRecord::Migration def self.up create_table :ward_profiles do |t| t.date :quarter t.integer :total_families t.integer :active t.integer :less_active t.integer :unknown t.integer :not_interested t.integer :dnc t.integer :new t.integer :moved t.integer :visited t.timestamps end end def self.down drop_table :ward_profiles end end
class CreateDailyMeals < ActiveRecord::Migration def change create_table :daily_meals do |t| t.belongs_to :recipe, index: true t.belongs_to :meal_plan, index: true t.timestamps end end end
# Exercise 7: More Printing # https://learnrubythehardway.org/book/ex7.html # prints a string puts "Mary had a little lamb." # prints a string with another string embedded puts "Its fleece was white as #{'snow'}." # prints a string puts "And everywhere that Mary went." # prints a string multiplied by 10, as a result the text should appear reapeted in the line puts "." * 10 # what'd that do? I think prints 10 dots in a line # declare a variable and store a character inside end1 = "C" # declare a variable and store a character inside end2 = "h" # declare a variable and store a character inside end3 = "e" # declare a variable and store a character inside end4 = "e" # declare a variable and store a character inside end5 = "s" # declare a variable and store a character inside end6 = "e" # declare a variable and store a character inside end7 = "B" # declare a variable and store a character inside end8 = "u" # declare a variable and store a character inside end9 = "r" # declare a variable and store a character inside end10 = "g" # declare a variable and store a character inside end11 = "e" # declare a variable and store a character inside end12 = "r" # whatch that print vs. puts on this line what's it do? # prints the concatenation of 6 variables and do not enter return at the end of the line print end1 + end2 + end3 + end4 + end5 + end6 # prints the concatenation of 6 variables and enter a return at the end of the line puts end7 + end8 +end9 + end10 + end11 + end12
Rails.application.routes.draw do resource :offers_requests, only: [:new, :create] root 'offers_requests#new' end
class TopicsController < ApplicationController before_action :authenticate_user before_action :ensure_correct_user, {only: [:edit, :update, :destroy]} def new @topic = Topic.new end def create @topic = Topic.new( description: params[:description], user_id: @current_user.id ) if @topic.save flash[:notice] = "投稿完了!" redirect_to("/topics/index") else render("topics/new") end end def index @topics = Topic.all.order(created_at: :desc) end def show @topic = Topic.find_by(id: params[:id]) @user = @topic.user @likes_count = Like @likes_count = Like.where(topic_id: @topic.id).count end def edit @topic = Topic.find_by(id: params[:id]) end def update @topic = Topic.find_by(id: params[:id]) @topic.description = params[:description] if @topic.save flash[:notice] = "投稿を編集しました" redirect_to("/topics/index") else render("topics/edit") end end def destroy @topic = Topic.find_by(id: params[:id]) @topic.destroy flash[:notice] = "投稿を削除しました" redirect_to("/topics/index") end def ensure_correct_user @topic = Topic.find_by(id: params[:id]) if @topic.user_id != @current_user.id flash[:notice] = "権限がありません" redirect_to("/topics/index") end end end
class Report class GroupedCommentsFetcher def initialize(report:, user:) @report = report @user = user end def all comments.group_by(&:associated_activity) end private attr_reader :report, :user def comments if user.partner_organisation? report.comments.includes( owner: [:organisation], commentable: [ :parent_activity, parent: [ parent: [:parent] ] ] ) else report.comments.includes(commentable: [:parent_activity]) end end end end
class PruneOldAccountsJob < ApplicationJob queue_as :default def perform(*args) accounts = Account.without_matches.sole_accounts.not_recently_updated.includes(:user) if accounts.count < 1 Rails.logger.info 'PruneOldAccountsJob no old single accounts without matches' return end Rails.logger.info "PruneOldAccountsJob deleting #{accounts.count} account(s) and their users" users = accounts.map(&:user) accounts.destroy_all users.map(&:destroy) end end
class ValidatesOptions attr_accessor :validations, :column def initialize(column, options = {}) @validations = Hash.new { |hash, key| hash[key] = false } options.each do |validation, status| validations[validation] = status end @column = column end end module Validatable def validates(column, options = {}) self.validatable_options = ValidatesOptions.new(column, options) define_method("valid?") do self.class.validatable_options.validations.select { |_, v| v }.each do |validation, _| send(validation, column) end errors.empty? end end def validatable_options @validatable_options ||= {} end def validatable_options=(validatable_options) @validatable_options = validatable_options end end module ValidationHelpers def uniqueness(column) return if (self.class.where(column => send(column)).map(&:id) - [id]).empty? errors.add(column, "has already been taken") end def presence(column) return if send(column).present? errors.add(column, "must not be blank") end end class SQLObject extend Validatable include ValidationHelpers end
module AuthService class LogoutUser prepend SimpleCommand attr_accessor :user def initialize(user = nil) @user = user end def call user.token = nil user.save! end end end
require 'spec_helper' describe User do context 'validations' do let(:user) { create(:user) } it 'should be valid with mandatory attributes' do expect(user).to be_valid end it 'should not be valid without an email' do user.email = nil expect(user).not_to be_valid end it 'should not be valid without a name' do user.name = nil expect(user).not_to be_valid end it 'should not be valid with a short password' do user.password = 'short' user.password_confirmation = 'short' expect(user).not_to be_valid end it 'should not be valid with a empty password' do user.password = '' user.password_confirmation = '' expect(user).not_to be_valid end end context 'scopes' do describe '::organization' do let(:organization) { create(:organization) } it 'should return all the users that belongs to an organization' do create(:user) # an user that belongs to another organization organization_total_users = rand(1..10).times do create(:user, organization: organization) end users = User.organization(organization.id) expect(users.count).to eql(organization_total_users) end end describe '::email' do let(:user) { create(:user) } it 'should return all the users with that match a given email' do rand(1..10).times { create(:user) } users = User.email(user.email) expect(users.count).to eql(1) end end describe '::names' do let!(:user) { create(:user, name: 'Benito Juárez García') } it 'should return all the users that match a given name' do rand(1..10).times { create(:user) } users = User.names('Benito') expect(users.count).to eql(1) end end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name => 'Daley', :city => cities.first) Post.delete_all Admin.delete_all Comment.delete_all Post.create(:title => 'Cheese Sandwich', :author => 'angry beaver', :content => %{##i had a sandwich it was *delicious* for me >i love sandwiches [posts listing][posts] * etc * sdf * dfsaf Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis diam at sem faucibus rhoncus ut in arcu. Maecenas eu tortor vitae orci rutrum dictum sit amet eget dolor. Nunc sodales, ipsum nec varius euismod, massa quam sollicitudin erat, nec gravida dui massa nec justo. Praesent egestas porta tellus, vel iaculis urna elementum ac. Nullam adipiscing augue non metus tempus ultricies. Nullam lacus erat, vestibulum eu cursus a, venenatis quis arcu. Pellentesque sollicitudin faucibus vestibulum. Vivamus tempus tortor vitae lectus vehicula sollicitudin. Nunc et tristique urna. Aliquam ac urna non risus fermentum consequat at eget elit. Cras eu nunc eget lectus volutpat accumsan. Phasellus vel odio diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut luctus lobortis dolor, eu porttitor felis consectetur quis. Curabitur in felis id ipsum eleifend feugiat a eu dui. In facilisis justo at nulla euismod id eleifend nunc posuere. Ut mattis blandit nulla at euismod. Quisque at orci metus, nec dictum est. In feugiat augue dui, sed commodo dolor. Vestibulum porttitor velit non nunc consequat non scelerisque erat scelerisque. Ut non fringilla risus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis sed porttitor magna. Pellentesque commodo tristique mauris, non vehicula augue laoreet et. Maecenas a massa tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin nec nulla in libero vestibulum tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam condimentum convallis ligula, eu tempor metus volutpat sit amet. Nam posuere feugiat lacus at suscipit. Curabitur tempor consectetur erat, in semper metus imperdiet sit amet. Vestibulum lorem neque, lacinia ut cursus eu, sagittis a eros. [posts]: /posts}, :published => true) Post.create(:title => 'splat', :author => 'angry beaver', :content => %{##i had a sandwich it was *delicious* for me >i love sandwiches [posts listing][posts] * etc * sdf * dfsaf Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis diam at sem faucibus rhoncus ut in arcu. Maecenas eu tortor vitae orci rutrum dictum sit amet eget dolor. Nunc sodales, ipsum nec varius euismod, massa quam sollicitudin erat, nec gravida dui massa nec justo. Praesent egestas porta tellus, vel iaculis urna elementum ac. Nullam adipiscing augue non metus tempus ultricies. Nullam lacus erat, vestibulum eu cursus a, venenatis quis arcu. Pellentesque sollicitudin faucibus vestibulum. Vivamus tempus tortor vitae lectus vehicula sollicitudin. Nunc et tristique urna. Aliquam ac urna non risus fermentum consequat at eget elit. Cras eu nunc eget lectus volutpat accumsan. Phasellus vel odio diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut luctus lobortis dolor, eu porttitor felis consectetur quis. Curabitur in felis id ipsum eleifend feugiat a eu dui. In facilisis justo at nulla euismod id eleifend nunc posuere. Ut mattis blandit nulla at euismod. Quisque at orci metus, nec dictum est. In feugiat augue dui, sed commodo dolor. Vestibulum porttitor velit non nunc consequat non scelerisque erat scelerisque. Ut non fringilla risus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis sed porttitor magna. Pellentesque commodo tristique mauris, non vehicula augue laoreet et. Maecenas a massa tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin nec nulla in libero vestibulum tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam condimentum convallis ligula, eu tempor metus volutpat sit amet. Nam posuere feugiat lacus at suscipit. Curabitur tempor consectetur erat, in semper metus imperdiet sit amet. Vestibulum lorem neque, lacinia ut cursus eu, sagittis a eros. [posts]: /posts}, :published => true) Post.create(:title => 'Cheese Sandwich 2', :author => 'angry beaver', :content => %{##i had a sandwich it was *delicious* for me >i love sandwiches [posts listing][posts] * etc * sdf * dfsaf Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis diam at sem faucibus rhoncus ut in arcu. Maecenas eu tortor vitae orci rutrum dictum sit amet eget dolor. Nunc sodales, ipsum nec varius euismod, massa quam sollicitudin erat, nec gravida dui massa nec justo. Praesent egestas porta tellus, vel iaculis urna elementum ac. Nullam adipiscing augue non metus tempus ultricies. Nullam lacus erat, vestibulum eu cursus a, venenatis quis arcu. Pellentesque sollicitudin faucibus vestibulum. Vivamus tempus tortor vitae lectus vehicula sollicitudin. Nunc et tristique urna. Aliquam ac urna non risus fermentum consequat at eget elit. Cras eu nunc eget lectus volutpat accumsan. Phasellus vel odio diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut luctus lobortis dolor, eu porttitor felis consectetur quis. Curabitur in felis id ipsum eleifend feugiat a eu dui. In facilisis justo at nulla euismod id eleifend nunc posuere. Ut mattis blandit nulla at euismod. Quisque at orci metus, nec dictum est. In feugiat augue dui, sed commodo dolor. Vestibulum porttitor velit non nunc consequat non scelerisque erat scelerisque. Ut non fringilla risus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis sed porttitor magna. Pellentesque commodo tristique mauris, non vehicula augue laoreet et. Maecenas a massa tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin nec nulla in libero vestibulum tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam condimentum convallis ligula, eu tempor metus volutpat sit amet. Nam posuere feugiat lacus at suscipit. Curabitur tempor consectetur erat, in semper metus imperdiet sit amet. Vestibulum lorem neque, lacinia ut cursus eu, sagittis a eros. [posts]: /posts}, :published => false) Admin.create(:username => 'Admin', :password => 'passwordpasswordpasswordpassword')
class Api::FilmsController < ApplicationController skip_before_action :verify_authenticity_token def actors film = Film.find(params[:film_id]) actors = film.actors if actors render json: actors else render json: 404 end end def index films = Film.sorted # films = Film.search(params[:film_search]).sorted render json: films # films = Film.search(params[:film_search]).sorted end def search films = Film.search(params[:film_search]).sorted render json: films end def show film = Film.find(params[:id]) if film render json: film else render json: 404 end end def new film = Film.new render json: film end def create film = Film.new(film_params) if film.save render json: { message: "Success" } else render json: { message: "Failure" } end end private def film_params params.require(:film).permit(:title, :language_id, :rental_duration, :rental_rate, :replacement_cost, :release_year, :description, :rating, :special_features) end end
require "aethyr/core/actions/commands/aconfig" require "aethyr/core/registry" require "aethyr/core/input_handlers/admin/admin_handler" module Aethyr module Core module Commands module Aconfig class AconfigHandler < Aethyr::Extend::AdminHandler def self.create_help_entries help_entries = [] command = "aconfig" see_also = nil syntax_formats = ["ACONFIG", "ACONFIG RELOAD", "ACONFIG [SETTING] [VALUE]"] aliases = nil content = <<'EOF' Sorry no help has been written for this command yet EOF help_entries.push(Aethyr::Core::Help::HelpEntry.new(command, content: content, syntax_formats: syntax_formats, see_also: see_also, aliases: aliases)) return help_entries end def initialize(player) super(player, ["aconfig"], help_entries: AconfigHandler.create_help_entries) end def self.object_added(data) super(data, self) end def player_input(data) super(data) case data[:input] when /^aconfig(\s+reload)?$/i setting = "reload" if $1 $manager.submit_action(Aethyr::Core::Actions::Aconfig::AconfigCommand.new(@player, {:setting => setting})) when /^aconfig\s+(\w+)\s+(.*)$/i setting = $1 value = $2 $manager.submit_action(Aethyr::Core::Actions::Aconfig::AconfigCommand.new(@player, {:setting => setting, :value => value})) end end private end Aethyr::Extend::HandlerRegistry.register_handler(AconfigHandler) end end end end
require 'test_helper' class ExercicesControllerTest < ActionDispatch::IntegrationTest setup do @exercice = exercices(:one) end test "should get index" do get exercices_url assert_response :success end test "should get new" do get new_exercice_url assert_response :success end test "should create exercice" do assert_difference('Exercice.count') do post exercices_url, params: { exercice: { author: @exercice.author, content: @exercice.content, course_id: @exercice.course_id, search: @exercice.search, slug: @exercice.slug, title: @exercice.title, user_id: @exercice.user_id } } end assert_redirected_to exercice_url(Exercice.last) end test "should show exercice" do get exercice_url(@exercice) assert_response :success end test "should get edit" do get edit_exercice_url(@exercice) assert_response :success end test "should update exercice" do patch exercice_url(@exercice), params: { exercice: { author: @exercice.author, content: @exercice.content, course_id: @exercice.course_id, search: @exercice.search, slug: @exercice.slug, title: @exercice.title, user_id: @exercice.user_id } } assert_redirected_to exercice_url(@exercice) end test "should destroy exercice" do assert_difference('Exercice.count', -1) do delete exercice_url(@exercice) end assert_redirected_to exercices_url end end
# encoding: utf-8 class Contentr::Admin::ParagraphsController < Contentr::Admin::ApplicationController before_filter :find_page_or_site def index @paragraphs = @page.paragraphs.order_by(:area_name, :asc).order_by(:position, :asc) end def new @area_name = params[:area_name] if params[:type].present? @paragraph = paragraph_type_class.new(area_name: @area_name) render 'new', layout: false else render 'new_select' end end def create @paragraph = paragraph_type_class.new(paragraph_params) @paragraph.area_name = params[:area_name] @paragraph.page = @page @page_or_site.paragraphs << @paragraph if @page_or_site.save! @paragraph.publish! if paragraph_type_class.auto_publish if request.xhr? @paragraph = @paragraph.for_edit render action: 'show', layout: false else redirect_to :back, notice: 'Paragraph wurde erfolgreich erstellt' end else render :action => :new end end def edit @paragraph = Contentr::Paragraph.find_by(id: params[:id]) @paragraph.for_edit render action: 'edit', layout: false end def update @paragraph = Contentr::Paragraph.unscoped.find(params[:id]) if params[:paragraph].has_key?("remove_image") @paragraph.image_asset_wrapper_for(params[:paragraph]["remove_image"]).remove_file!(@paragraph) params[:paragraph].delete("remove_image") end if @paragraph.update(paragraph_params) if request.xhr? @paragraph = @paragraph.for_edit render action: 'show', layout: false else redirect_to :back, notice: 'Paragraph wurde erfolgreich aktualisiert.' end else render :action => :edit end end def show @paragraph = @page_or_site.paragraphs.find(params[:id]) @paragraph.for_edit render action: 'show', layout: false end def publish @paragraph = Contentr::Paragraph.find_by(id: params[:id]) @paragraph.publish! redirect_to(:back, notice: 'Published this paragraph') end def revert @paragraph = Contentr::Paragraph.find_by(id: params[:id]) @paragraph.revert! redirect_to(:back, notice: 'Reverted this paragraph') end def show_version @paragraph = Contentr::Paragraph.find_by(id: params[:id]) current = params[:current] == "1" ? true : false render text: view_context.display_paragraph(@paragraph, current) end def destroy paragraph = Contentr::Paragraph.find_by(id: params[:id]) paragraph.destroy redirect_to :back, notice: 'Paragraph was destroyed' end def reorder paragraphs_ids = params[:paragraph] paragraphs = @page_or_site.paragraphs_for_area(params[:area_name]).sort { |x,y| paragraphs_ids.index(x.id.to_s) <=> paragraphs_ids.index(y.id.to_s) } paragraphs.each_with_index { |p, i| p.update_column(:position, i) } head :ok end def display paragraph = Contentr::Paragraph.find_by(id: params[:id]) paragraph.update(visible: true) redirect_to :back, notice: t('.message') end def hide paragraph = Contentr::Paragraph.find_by(id: params[:id]) paragraph.update(visible: false) redirect_to :back, notice: t('.message') end protected def paragraph_type_class paragraph_type_string = params[:type] # e.g. Contentr::HtmlParagraph paragraph_type_class = paragraph_type_string.classify.constantize # just to be sure paragraph_type_class if paragraph_type_class < Contentr::Paragraph end def find_page_or_site if (params[:site] == 'true') @page_or_site = Contentr::Site.default @page = Contentr::Page.find_by(id: params[:page_id]) else @page_or_site = Contentr::Page.find_by(id: params[:page_id]) @page = @page_or_site end end protected def paragraph_params type = params['type'] || Contentr::Paragraph.unscoped.find(params[:id]).class.name params.require(:paragraph).permit(*type.constantize.permitted_attributes) end end
JSONAPI.configure do |config| # Built in paginators are :none, :offset, :paged config.default_paginator = :paged config.default_page_size = 10 config.maximum_page_size = 50 config.top_level_meta_include_record_count = true config.top_level_meta_record_count_key = :record_count end
#mastername.rb Puppet::Functions.create_function(:mastername) do dispatch :mastername do param 'String', :filename optional_param 'String', :foo return_type 'String' end def mastername(*arguments) #puts filename.to_s File.open('/etc/puppetlabs/puppet/puppet.conf').grep(/server\s*=/).join.split(' ').slice(2) # Below line works as welll. Where \= is escaped #File.open('/etc/puppetlabs/puppet/puppet.conf').grep(/server\s*\=/).join.split(' ').slice(2) end end
require 'rails_helper' RSpec.describe LoginController, :type => :controller do describe "POST #create (login)" do let(:user) { FactoryGirl.create(:person, name: "pepe", lastname: "lopez", email: "qw@qwe.com", password: "1")} it "authenticates user and redirects to root url index with id in session" do post :create, email: user.email, password: "1" session[:current_user_id] = user.id expect(response).to redirect_to(root_url) expect(session[:current_user_id]).to eq(user.id) end it "with wrong password flashes error and renders the new form again" do post :create, email: user.email, password: "wrong" expect(response).to render_template(:new) expect(session[:current_user_id]).to be nil end it "with wrong email flashes error and renders the new form again" do post :create, email: "wrong@a.com", password: "1" expect(response).to render_template(:new) expect(session[:current_user_id]).to be nil end end describe "DELETE #destroy (logout)" do let(:user) { FactoryGirl.create(:person, name: "pepe", lastname: "lopez", email: "email@a.com", password: "1") } it "deletes session id and redirects to root (JS format)" do session[:current_user_id] = 1 delete :destroy, format: :js expect(session[:current_user_id]).to be nil expect(response.body).to eq("window.location.href='#{root_path}'") end it "deletes session id and redirects to root (HTML format)" do session[:current_user_id] = 1 delete :destroy, format: :html expect(session[:current_user_id]).to be nil expect(response).to redirect_to(root_url) end end end
class Card < ApplicationRecord validates :original_text, :translated_text, presence: { message: 'Все поля должны быть заполнены!' } validate :fields_equal? validate :set_review_date_to_now private def fields_equal? if self.original_text.to_s.downcase == self.translated_text.to_s.downcase errors.add(:original_text, "Не может совпадать с ответом") errors.add(:translated_text, "Не может совпадать с вопросом") end end def set_review_date_to_now self.review_date = Time.current end end
class StartpageController < ApplicationController def index @user = current_user @blog_posts = BlogPost.limit(3) end end
module ActiveSupport module Cache class FileStore < Store def read(name, options = nil) super file_name = real_file_path(name) expires = expires_in(options) if exist_without_instrument?(file_name, expires) File.open(file_name, 'rb') { |f| Marshal.load(f) } end end def exist?(name, options = nil) super File.exist?(real_file_path(name)) exist_without_instrument?(real_file_path(name), expires_in(options)) end def exist_without_instrument?(file_name, expires) File.exist?(file_name) && (expires <= 0 || Time.now - File.mtime(file_name) < expires) end end end end
class MyList < ApplicationRecord validates :movie_id, uniqueness: { scope: :user_id} belongs_to :movie belongs_to :user end
# frozen_string_literal: true require "webauthn/error" module WebAuthn module AttestationStatement class FormatNotSupportedError < Error; end ATTESTATION_FORMAT_NONE = "none" ATTESTATION_FORMAT_FIDO_U2F = "fido-u2f" ATTESTATION_FORMAT_PACKED = 'packed' ATTESTATION_FORMAT_ANDROID_SAFETYNET = "android-safetynet" ATTESTATION_FORMAT_ANDROID_KEY = "android-key" ATTESTATION_FORMAT_TPM = "tpm" def self.from(format, statement) case format when ATTESTATION_FORMAT_NONE require "webauthn/attestation_statement/none" WebAuthn::AttestationStatement::None.new(statement) when ATTESTATION_FORMAT_FIDO_U2F require "webauthn/attestation_statement/fido_u2f" WebAuthn::AttestationStatement::FidoU2f.new(statement) when ATTESTATION_FORMAT_PACKED require "webauthn/attestation_statement/packed" WebAuthn::AttestationStatement::Packed.new(statement) when ATTESTATION_FORMAT_ANDROID_SAFETYNET require "webauthn/attestation_statement/android_safetynet" WebAuthn::AttestationStatement::AndroidSafetynet.new(statement) when ATTESTATION_FORMAT_ANDROID_KEY require "webauthn/attestation_statement/android_key" WebAuthn::AttestationStatement::AndroidKey.new(statement) when ATTESTATION_FORMAT_TPM require "webauthn/attestation_statement/tpm" WebAuthn::AttestationStatement::TPM.new(statement) else raise FormatNotSupportedError, "Unsupported attestation format '#{format}'" end end end end
# -*- encoding : utf-8 -*- module V1 module Strokes module Entities class Strokes < Grape::Entity expose :uuid expose :sequence expose :distance_from_hole expose :point_of_fall expose :penalties expose :club end class Scorecard < Grape::Entity expose :score expose :putts expose :penalties end class StrokeAndScorecard < Grape::Entity expose :stroke expose :scorecard, using: Scorecard end end end class StrokesAPI < Grape::API resources :strokes do desc '击球记录列表' params do requires :scorecard_uuid, type: String, desc: '记分卡标识' end get '/' do begin scorecard = Scorecard.find_uuid(params[:scorecard_uuid]) raise PermissionDenied.new unless scorecard.player.user_id == @current_user.id raise InvalidScoringType.new if scorecard.player.scoring_type_simple? present scorecard.strokes, with: Strokes::Entities::Strokes rescue ActiveRecord::RecordNotFound api_error!(10002) rescue PermissionDenied api_error!(10003) rescue InvalidScoringType api_error!(20103) end end end end end
class CreateForecasts < ActiveRecord::Migration[5.1] def change create_table :forecasts do |t| t.integer :provider, default: 0 t.string :spot t.json :forecast t.timestamps end add_index :forecasts, [:spot, :provider], unique: true end end
FactoryGirl.define do sequence :email do |n| "email#{n}@factory.com" end factory :user do |f| f.firstname Faker::Name.first_name f.lastname Faker::Name.last_name f.email #this email field is unique for every user because of sequencing defined above f.password Faker::Lorem.characters(8) end end
require 'rails_helper' RSpec.describe 'questions/index.json.jbuilder', type: :view do let(:json_result) { JSON.parse(rendered) } let(:questions) { create_list(:question, 2) } before(:each) do assign(:questions, questions) render end it 'renders a JSON list of the right size' do expect(json_result.count).to eq 2 end it 'renders all attributes of the passed questions' do json_result.each_with_index do |item, i| %w(id title body answer).each do |attr| expect(item[attr]).to eq questions[i].send(attr) end %w(created_at updated_at).each do |attr| expected = questions[i].send(attr).to_i date = DateTime.parse(item[attr]).to_i expect(date).to eq expected end end end it "adds each question's URL" do json_result.each_with_index do |item, i| expect(item['url']).to eq question_url(questions[i], format: :json) end end end
module InContact class Api attr_reader :token def initialize @token = InContact::Tokens.get end def agents @agents ||= create_resource(InContact::Resources::AGENTS) end def contacts @contacts ||= create_resource(InContact::Resources::CONTACTS) end def agent_sessions @agent_sessions ||= create_resource(InContact::Resources::AGENT_SESSIONS) end def call_lists @call_lists ||= create_resource(InContact::Resources::CALL_LISTS) end private def create_resource(resource) resource_model = "InContact::#{resource}".constantize data_model = "InContact::Responses::#{resource.singularize}Response".constantize connection = create_connection(data_model) resource_model.new(connection) end def create_connection(data_model) url = token.resource_server_base_uri authorization = token.authorization options = { default_data_model: data_model } InContact::Connection.new(url, authorization, options) end end end
require_relative 'base_page' class BoxCigarsPage < BasePage path '/cigars/box-cigars' validate :url, %r{/cigars/box-cigars(?:\?.*|)$} validate :title, /^#{Regexp.escape('Box of Cigars: Box Selections Starting Under $20 | Famous Smoke')}$/ end
class CreateFilms < ActiveRecord::Migration def change create_table :films do |t| t.string :title t.integer :year t.string :slogan t.integer :director_id t.integer :budget t.float :rating t.float :our_rating t.integer :duration t.timestamps end end end
require 'test_helper' class UserTest < ActiveSupport::TestCase # Replace this with your real tests. test "is reg finished" do user = User.create({:email=>"email@mail.com",:password=>"pass"}) assert_equal false, user.is_reg_finished user.is_reg_finished=true user.update_attributes(:email=>'mod@mail.com') assert_equal true, user.is_reg_finished end test "login?" do assert User.login?("one@mail.com",'one'),'登录失败' resut= User.login?("one@mail.com1",'one1') assert_equal -1, resut resut = User.login?("one@mail.com",'one1') assert_equal -2, resut end test "new around me user" do assert_difference "users(:three).around_me_update_queue().size" do users(:one).update_attribute(:last_position_x,2) users(:one).update_attribute(:last_position_y,2) end end test "new around me user action add" do users(:one).update_attribute(:last_position_x,2) users(:one).update_attribute(:last_position_y,2) new_users = users(:three).around_me_update_queue() new_users.each do | user | assert_equal "Add", user.action end end test "level around me user" do users(:one).update_attribute(:last_position_x,2) users(:one).update_attribute(:last_position_y,2) assert_difference "users(:three).around_me_update_queue().size",0 do users(:three).update_attribute(:last_position_x,22) users(:three).update_attribute(:last_position_y,22) end end test "level around me user action del" do users(:one).update_attribute(:last_position_x,2) users(:one).update_attribute(:last_position_y,2) users(:three).around_me_update_queue().size users(:three).update_attribute(:last_position_x,22) users(:three).update_attribute(:last_position_y,22) del_users = users(:three).around_me_update_queue() del_users .each do | user | assert_equal "Del", user.action end end test "get uncatch msg by xy" do msgs = users(:three).get_msgs() assert_equal(3,msgs.size) assert_equal 'Add',msgs.first.action assert_equal 'one',msgs.first.poster_name end test "get useless msg by xy" do user3 =users(:three) msgs = user3.get_msgs assert_equal 3, msgs.size msgs = user3.get_msgs() assert_equal(0,msgs.size) messages(:two).update_attribute("position_x",10) msgs = user3.get_msgs assert_equal(1,msgs.size) assert_equal 'Del',msgs.first.action assert_equal 2,msgs.first.id end end
class AddColumnHasBeenAcceptedToJoins < ActiveRecord::Migration[5.2] def change add_column :pet_applications, :was_approved, :boolean end end
# frozen_string_literal: true ActiveAdmin.register User do menu priority: 2 actions :index, :edit, :show filter :aasm_state, as: :select, label: 'State' index as: :table do column I18n.t('admin.content') do |user| link_to image_tag(user.image.avatar.url), admin_user_path(user.id) end column I18n.t('admin.first_name'), :first_name column I18n.t('admin.last_name'), :last_name column I18n.t('admin.nickname'), :nickname column I18n.t('admin.link') do |u| link_to u.urls, u.urls end column I18n.t('admin.photoposts') do |user| user.photoposts.count end column I18n.t('admin.rating') do |user| user.ratings.count end column I18n.t('admin.comments') do |user| user.comments.count end state_column I18n.t('admin.status'), :aasm_state column I18n.t('admin.moderate') do |user| link_to 'Edit', edit_admin_user_path(user.id) end end show do |f| render 'show_form', user: f tabs do tab "#{I18n.t('admin.photoposts')} #{f.photoposts.count}" do render 'photoposts', photoposts: f.photoposts end tab "#{I18n.t('admin.comments')} #{f.comments.count}" do render 'comments', comments: f.comments.page(params[:page]) end tab "#{I18n.t('admin.rating')} #{f.ratings.count}" do render 'rating', ratings: f.ratings.page(params[:page]) end end end form do |f| f.para 'Ban reason: ' + f.object.ban_reason unless f.object.ban_reason.blank? image_tag f.object.image.admin.url f.para f.object.first_name + ' ' + f.object.last_name, class: 'reported-name' f.para link_to f.object.nickname, f.object, class: 'name-link' tabs do tab 'Reports' do render 'report_table' end tab 'Photoposts' do render 'photoposts', photoposts: f.object.photoposts end end if f.object.banned? f.button 'Restore', formaction: :restore else f.input :ban_reason f.button 'Ban', formaction: :ban end end member_action :ban, method: :patch do resource.ban_reason = params[:user][:ban_reason] resource.ban! redirect_to edit_admin_user_path(resource.id) end member_action :restore, method: :patch do resource.ban_reason = '' if ReportReason.find_by(user_id: resource.id).nil? resource.restore! else resource.report! end redirect_to edit_admin_user_path(resource.id) end end
class FieldOfView def initialize(options=Hash.new, block&) @light_passes = block& @options = { :topology => :eight } options.each { |k, v| @options[k] = v } end def compute(x, y, r, block&) end private def get_circle(cx, cy, r) result = Array.new dirs, count_factor, start_offset = nil if @options[:topology] == :four count_factor = 1 start_offset = [0, 1] dirs = [ directions[:eight][7], directions[:eight][1], directions[:eight][3], directions[:eight][5] ] elsif @options[:topology] == :six dirs = directions[:six] count_factor = 1 start_offset = [-1, 1] elsif @options[:topology] == :eight dirs = directions[:four] count_factor = 2 start_offset = [-1, 1] end x = cx + (start_offset[0] * r) y = cy + (start_offset[1] * r) (0..dirs.length-1).each do |i| (0..((r*count_factor) - 1)).each do |j| result << [x, y] x += dirs[i][0] y += dirs[i][1] end end result end def directions(v) dirs = { :four => [ [ 0, -1], [ 1, 0], [ 0, 1], [-1, 0] ], :eight => [ [ 0, -1], [ 1, -1], [ 1, 0], [ 1, 1], [ 0, 1], [-1, 1], [-1, 0], [-1, -1] ], :six => [ [-1, -1], [ 1, -1], [ 2, 0], [ 1, 1], [-1, 1], [-2, 0] ] } dirs[v] end end
Given /^provider "([^\"]*)" has valid payment gateway$/ do |provider_name| provider_account = Account.find_by_org_name!(provider_name) provider_account.update_attribute(:payment_gateway_type, :bogus) end Given /^the provider has a deprecated payment gateway$/ do @provider.gateway_setting.attributes = { gateway_type: :authorize_net, gateway_settings: { login: 'foo', password: 'bar' } } # to prevent ActiveRecord::RecordInvalid since the payment gateway has been deprecated @provider.gateway_setting.save!(validate: false) # We cannot use update_columns with Oracle end
require 'quaker/tag_matcher' require 'deep_merge' module Quaker class Templates def apply services templates = services.select {|name, _| template?(name)} services .reject {|name, _| template?(name)} .inject({}) {|acc, (name, spec)| acc.update(name => extend_with_matching_templates(spec, templates)) } end def extend_with_matching_templates service, templates templates .select {|_, spec| Quaker::TagMatcher::match(service["tags"], spec["tags"])} .inject(service) {|svc, (_, spec)| filtered_template_content = spec .select{|name, _| name != 'tags' } svc.deep_merge(filtered_template_content) } end def template?(k) !!(k =~ /_template$/) end end end
require File.expand_path(File.dirname(__FILE__) + "/../util_helper") class QaQuestion include UtilHelper def initialize(title, body, photos) if title == nil @title = "Question_" + random_number else @title = title end if body == nil @body = "Question_Body_" + random_number else @body = body end @photos = photos end def title @title end def body @body end def photos @photos end end
Rails.application.routes.draw do mount_devise_token_auth_for 'User', at: 'auth' scope module: 'api' do namespace :v1 do resources :tracked_times, only: [:index, :create] end end end
class Article < ActiveRecord::Base has_and_belongs_to_many :tags, join_table: "articles_tags" accepts_nested_attributes_for :tags end
Puppet::Type.newtype(:modprobe) do desc <<-EOT Load or unload a kernel module. EOT ensurable do desc "What state the kernel module should be in." newvalue(:present) do provider.create end newvalue(:absent) do provider.destroy end defaultto :present end newparam(:name, :namevar => true) do desc "The name of the kernel module to load or unload." end end
require 'rails_helper' describe User do it "is valid with a valid email and password" do user = build(:user) expect(user).to be_valid end it "is invalid without a valid email address" do user = build(:user, email: "not_an_email") expect(user).to_not be_valid end end
class LayersController < ApplicationController layout 'layerdetail', only: [:show, :edit, :export, :metadata] before_action :authenticate_user! , except: [:wms, :wms2, :show_kml, :show, :index, :metadata, :maps, :thumb, :tile, :trace, :id] before_action :check_administrator_role, only: [:publish, :toggle_visibility, :merge, :trace, :id] before_action :find_layer, only: [:show, :export, :metadata, :toggle_visibility, :update_year, :publish, :remove_map, :merge, :maps, :thumb, :trace, :id] before_action :check_if_layer_is_editable, only: [:edit, :update, :remove_map, :update_year, :update, :destroy] rescue_from ActiveRecord::RecordNotFound, with: :bad_record def thumb redirect_to @layer.thumb end def index # sort_init('created_at', {default_order: "desc"}) # session[@sort_name] = nil #remove the session sort as we have percent # sort_update @query = params[:query] @field = %w(name description).detect{|f| f== (params[:field])} @field = "name" if @field.nil? if @query && @query != "null" #null will be set by pagless js if theres no query conditions = ["#{@field} ~* ?", '(:punct:|^|)'+@query+'([^A-z]|$)'] else conditions = nil end if params[:sort_key] == "percent" select = "*, round(rectified_maps_count::float / maps_count::float * 100) as percent" conditions.nil? ? conditions = ["maps_count > 0"] : conditions.add_condition('maps_count > 0') else select = "*" end if params[:sort_order] && params[:sort_order] == "desc" sort_nulls = " NULLS LAST" else sort_nulls = " NULLS FIRST" end @per_page = params[:per_page] || 20 # order_options = sort_clause + sort_nulls map = params[:map_id] if !map.nil? @map = Map.find(map) layer_ids = @map.layers.map(&:id) @layers = Layer.where(id: layer_ids).select('*, round(rectified_maps_count::float / maps_count::float * 100) as percent').where(conditions).order(order_options) @html_title = "Map Layer List for Map #{@map.id}" @page = "for_map" else @layers = Layer.select(select).where(conditions) @html_title = "Browse Map Layers" end if !user_signed_in? || request.format.json? @layers = @layers.where(is_visible: true) end @layers = @layers.page(params[:page] || 1).per(@per_page) if request.xhr? # for pageless : # #render partial: 'layer', collection: @layers render action: 'index.rjs' else respond_to do |format| format.html {render layout: "application"} format.xml { render xml: @layers.to_xml(root: "layers", except: [:uuid, :parent_uuid, :description]) {|xml| xml.tag!'total-entries', @layers.total_entries xml.tag!'per-page', @layers.per_page xml.tag!'current-page',@layers.current_page} } format.json {render json: {stat: "ok", items: @layers.to_a}.to_json(except: [:uuid, :parent_uuid, :description]), callback: params[:callback] } end end end #method returns json or xml representation of a layers maps def maps show_warped = params[:show_warped] unless show_warped == "0" lmaps = @layer.maps.warped.order(:map_type).page(params[:page] || 1).per(50) else lmaps = @layer.maps.order(:map_type).pagee(params[:page] || 1).per(50) end respond_to do |format| #format.json {render json: lmaps.to_json(stat: "ok",except: [:content_type, :size, :bbox_geom, :uuid, :parent_uuid, :filename, :parent_id, :map, :thumbnail])} format.json {render json: {stat: "ok", current_page: lmaps.current_page, per_page: lmaps.per_page, total_entries: lmaps.total_entries, total_pages: lmaps.total_pages, items: lmaps.to_a}.to_json(except: [:content_type, :size, :bbox_geom, :uuid, :parent_uuid, :filename, :parent_id, :map, :thumbnail]), callback: params[:callback] } format.xml {render xml: lmaps.to_xml(root: "maps",except: [:content_type, :size, :bbox_geom, :uuid, :parent_uuid, :filename, :parent_id, :map, :thumbnail]) {|xml| xml.tag!'total-entries', lmaps.total_entries xml.tag!'per-page', lmaps.per_page xml.tag!'current-page',lmaps.current_page} } end end def show @current_tab = "show" @selected_tab = 0 @disabled_tabs = [] unless @layer.rectified_maps_count > 0 #i.e. if the layer has no maps, then dont let people export @disabled_tabs = ["export"] end if user_signed_in? and (current_user.own_this_layer?(params[:id]) or current_user.has_role?("editor")) @maps = @layer.maps.order(:map_type).page(params[:page] || 1).per(30) else @disabled_tabs += ["edit"] @maps = @layer.maps.are_public.order(:map_type).page(params[:page] || 1).per(30) end @html_title = "Map Layer "+ @layer.id.to_s + " " + @layer.name.to_s if request.xhr? unless params[:page] @xhr_flag = "xhr" render action: "show", layout: "layer_tab_container" else render action: "show_maps.rjs" end else respond_to do |format| format.html {render layout: "layerdetail"}# show.html.erb #format.json {render json: @layer.to_json(except: [:uuid, :parent_uuid, :description])} format.json {render json: {stat: "ok", items: @layer}.to_json(except: [:uuid, :parent_uuid, :description]), callback: params[:callback] } format.xml {render xml: @layer.to_xml(except: [:uuid, :parent_uuid, :description])} format.kml {render action: "show_kml", layout: false} end end end def new #assume that the user is logged in @html_title = "Make new map layer -" @layer = Layer.new @maps = current_user.maps respond_to do |format| format.html {render layout: "application"}# show.html.erb end end def create @layer = Layer.new(layer_params) #@maps = current_user.maps.warped @layer.user = current_user #@layer.maps = Map.find(params[:map_ids]) if params[:map_ids] if params[:map_ids] selected_maps = Map.find(params[:map_ids]) selected_maps.each {|map| @layer.maps << map} end if @layer.save @layer.update_layer @layer.update_counts flash[:notice] = "Map layer was successfully created." redirect_to layer_url(@layer) else redirect_to new_layer_url end end def edit @layer = Layer.find(params[:id]) @selected_tab = 1 @current_tab = "edit" @html_title = "Editing map layer #{@layer.id} on" if (!current_user.own_this_layer?(params[:id]) and current_user.has_role?("editor")) @maps = @layer.user.maps else @maps = current_user.maps #current_user.maps.warped end if request.xhr? @xhr_flag = "xhr" render action: "edit", layout: "layer_tab_container" else respond_to do |format| format.html {render layout: "layerdetail"}# show.html.erb end end end def update @layer = Layer.find(params[:id]) @maps = current_user.maps @layer.maps = Map.find(params[:map_ids]) if params[:map_ids] if @layer.update_attributes(layer_params) @layer.update_layer @layer.update_counts flash.now[:notice] = "Map layer was successfully updated." #redirect_to layer_url(@layer) else flash.now[:error] = "The map layer was not able to be updated" end if request.xhr? @xhr_flag = "xhr" render action: "edit", layout: "layer_tab_container" else respond_to do |format| format.html { render action: "edit",layout: "layerdetail" } end end end def delete @layer = Layer.find(params[:id]) respond_to do |format| format.html {render layout: "application"} end end def destroy @layer = Layer.find(params[:id]) authorize! :destroy, @layer if @layer.destroy flash[:notice] = "Map layer deleted!" else flash[:notice] = "Map layer wasn't deleted" end respond_to do |format| format.html { redirect_to(layers_url) } format.xml { head :ok } end end def export @current_tab = "export" @selected_tab = 3 @html_title = "Export Map Layer "+ @layer.id.to_s if request.xhr? @xhr_flag = "xhr" render layout: "layer_tab_container" else respond_to do |format| format.html {render layout: "layerdetail"} end end end def metadata @current_tab = "metadata" @selected_tab = 4 #@layer_properties = @layer.layer_properties choose_layout_if_ajax end #ajax method def toggle_visibility @layer.is_visible = !@layer.is_visible @layer.save @layer.update_layer if @layer.is_visible update_text = "(Visible)" else update_text = "(Not Visible)" end render json: {message: update_text} end def update_year @layer.update_attributes(params[:layer]) render json: {message: "Depicts : " + @layer.depicts_year.to_s } end #merge this layer with another one #moves all child object to new parent def merge if request.get? #just show form render layout: 'application' elsif request.put? @dest_layer = Layer.find(params[:dest_id]) @layer.merge(@dest_layer.id) render text: "Map layer has been merged into new layer - all maps copied across! (functionality disabled at the moment)" end end def remove_map @map = Map.find(params[:map_id]) @layer.remove_map(@map.id) render text: "Dummy text - Map removed from this map layer " end def publish if @layer.rectified_percent < 100 render text: "Map layer has less than 100% of its maps rectified" #redirect_to action: 'index' else @layer.publish render text: "Map layer will be published (this functionality is disabled at the moment)" end end def trace redirect_to layer_path unless @layer.is_visible? && @layer.rectified_maps_count > 0 @overlay = @layer render "maps/trace", layout: "application" end def id redirect_to layer_path unless @layer.is_visible? && @layer.rectified_maps_count > 0 @overlay = @layer render "maps/id", layout: false end # called by id JS oauth def idland render "maps/idland", layout: false end private def check_if_layer_is_editable @layer = Layer.find(params[:id]) authorize! :update, @layer end #little helper method def snippet(thought, wordcount) thought.split[0..(wordcount-1)].join(" ") +(thought.split.size > wordcount ? "..." : "") end def find_layer @layer = Layer.find(params[:id]) end def choose_layout_if_ajax if request.xhr? @xhr_flag = "xhr" render layout: "layer_tab_container" end end def bad_record #logger.error("not found #{params[:id]}") respond_to do | format | format.html do flash[:notice] = "Map layer not found" redirect_to action: :index end format.json {render json: {stat: "not found", items: []}.to_json, status: 404} end end def store_location case request.parameters[:action] when "metadata" anchor = "Metadata_tab" when "export" anchor = "Export_tab" else anchor = "" end if request.parameters[:action] && request.parameters[:id] session[:return_to] = layer_path(id: request.parameters[:id], anchor: anchor) else session[:return_to] = request.request_uri end end def layer_params params.require(:layer).permit(:name, :description, :source_uri, :depicts_year) end end
class HorsesController < ApplicationController # GET /horses def index all_horses end # GET /horses/1 def show horse end # GET /horses/new def new new_horse end # POST /horses def create if new_horse(horse_params).save redirect_to new_horse, notice: 'Horse was successfully created.' else render :new end end # GET /horses/1/edit def edit horse end # PATCH/PUT /horses/1 def update if horse.update(horse_params) redirect_to horse, notice: 'Horse was successfully updated.' else render :edit end end # DELETE /horses/1 # DELETE /horses/1.json def destroy @horse.destroy redirect_to horses_url, notice: 'Horse was successfully destroyed.' end private def all_horses @horse ||= Horse.all end def new_horse(attrs={}) @horse ||= Horse.new(attrs) end def horse @horse ||= Horse.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def horse_params params.require(:horse).permit(:height, :name, :color) end end
require 'spec_helper' require 'httparty' describe TMDBParty::Movie do before(:each) do stub_get('/Movie.getInfo/en/json/key/1858', 'transformers.json') end let :transformers do HTTParty::Parser.call(fixture_file('transformers.json'), :json).first end let :transformers_movie do TMDBParty::Movie.new(transformers, TMDBParty::Base.new('key')) end it "should take an attributes hash and a TMDBParty::Base instance when initialized" do expect { TMDBParty::Movie.new({}, TMDBParty::Base.new('key')) }.to_not raise_error end describe "attributes" do it "should have a score when coming from search results" do TMDBParty::Movie.new({'score' => '0.374527342'}, TMDBParty::Base.new('key')).score.should == 0.374527342 end [:posters, :backdrops, :homepage, :trailer, :runtime, :genres, :cast, :countries, :tagline, :studios].each do |attribute| it "should load #{attribute} attribute by looking up the movie if it is missing" do movie = TMDBParty::Movie.new({ 'id' => 1858 }, TMDBParty::Base.new('key')) movie.send(attribute).should_not be_nil end it "should not look up the movie when #{attribute} is not missing" do tmdb = mock(TMDBParty::Base) movie = TMDBParty::Movie.new({ 'id' => 1858, attribute.to_s => transformers[attribute.to_s] }, tmdb) tmdb.should_not_receive(:get_info) movie.send(attribute) end end it "should have a release date" do transformers_movie.released.should == Date.new(2007, 7, 4) end it "should have a translated? attribute" do transformers_movie.should be_translated end it "should have a language" do transformers_movie.language.should == :en end it "should have a tagline" do transformers_movie.tagline.should == "Their war. Our world." end it "should have a certification" do transformers_movie.certification.should == "PG-13" end it "should have a last modified at timestamp" do transformers_movie.last_modified_at.should == Time.parse('2010-05-07 22:53:59 UTC') end it "should have a cast" do transformers_movie.cast.should have(36).members transformers_movie.cast.first.should be_instance_of(TMDBParty::CastMember) end it "should have a list of directors" do transformers_movie.directors.map { |p| p.name }.should == ['Michael Bay'] end it "should have a list of actors" do transformers_movie.should have(17).actors end it "should have a list of writers" do transformers_movie.writers.should == [] end it "should have a list of poster images" do transformers_movie.should have(10).posters poster = transformers_movie.posters.first poster.sizes.should include(:cover, :thumb, :mid, :original) end it "should have a list of backdrop images" do transformers_movie.should have(11).backdrops backdrop = transformers_movie.backdrops.first backdrop.sizes.should include(:thumb, :poster, :original) end it "should have a list of genres" do transformers_movie.should have(3).genres transformers_movie.genres.map { |g| g.name }.should include('Action', 'Adventure', 'Science Fiction') end it "should have a list of countries" do transformers_movie.should have(1).countries transformers_movie.countries.first.url.should == 'http://www.themoviedb.org/country/us' end it "should have a list of studios" do transformers_movie.should have(1).studios transformers_movie.studios.first.name.should == 'DreamWorks SKG' end end end
class CreateWorkAttributes < ActiveRecord::Migration def change create_table :work_attributes do |t| t.string :title t.text :summary t.text :to t.text :from t.boolean :current t.integer :workplace_id t.integer :user_id t.integer :added_by t.boolean :visible, :default => true t.timestamps end add_index :work_attributes, :user_id add_index :work_attributes, [:user_id, :workplace_id, :title] end end
INDUSTRIES = ['Advertising', 'Agriculture and Forestry', 'Architects', 'Arts and Cultures Industries', 'Catering', 'Charities', 'Clubs and Associations', 'Construction Industry', 'Dentists', 'Distribution and Transport', 'Doctors', 'Education', 'Engineering', 'Entertainment', 'Estate Agents', 'Financial Services', 'Friendly Societies', 'Housing', 'IT/Software', 'Manufacturing', 'Motor Retailers', 'Printing and Publishing', 'Public sector', 'Retail', 'Service Industries', 'Solicitors', 'Sub-Contractors', 'Telecommunications', 'Tourism and Travel Agents', 'Vets'] COMPANY_SIZES = ['<1', '1-10', '10-25', '25+'] SUBSERVICES = ["Business start-up and company formation", "Information Technology", "Limited company accounts", "Partnership / sole trader accounts", "Business plans", "Management advice to business", "Tax(CGT, Corporate, IHT, Personal and VAT)", "Company secretarial service", "Corporate finance", "Management accounting consultancy", "Management consultancy", "Share valuations", "Tax and NI investigations", "Benchmarking", "Business process improvements", "Corporate recovery", "Cost systems and control", "Data processing services", "Debt counselling", "Estate planning and executorship", "Expert witness", "Feasibility studies", "Internal audit and systems security", "Trusteeship / Trust Administration", "Bank loans and overdrafts (inc SFLGS)", "Business risk assessment", "Business plans (external and internal)", "Small scale equity issues", "Start-up Finance(inc using own funds)", "Divorce matrimonial", "Export finance planning and tax", "Grants and Finance (EU,government)", "Treasury", "Establishing a business overseas", "Arbitration", "Environmental auditing", "Leasing and hire purchase", "Asset Finance", "Annual Accounts", "Audit Services", "Business Advice", "Tax Services", "M&A/Transaction", "Bookkeeping", "Other"] SERVICES = [ "Annual Accounts", "Audit Services", "Business Consulting & Support", "Tax Services", "Formation / M&A", "Bookkeeping & Admin", "Insolvency and Arbitration", "Financing Support", "Other"] SERVICE_MAP = { "Business start-up and company formation" => "Formation / M&A", "Information Technology" => "Bookkeeping & Admin", "Limited company accounts" => "Annual Accounts", "Partnership / sole trader accounts" => "Annual Accounts", "Business plans" => "Business Consulting & Support", "Management advice to business" => "Business Consulting & Support", "Tax(CGT, Corporate, IHT, Personal and VAT)" => "Tax Services", "Company secretarial service" => "Bookkeeping & Admin", "Corporate finance" => "Financing Support", "Management accounting consultancy" => "Business Consulting & Support", "Management consultancy" => "Business Consulting & Support", "Share valuations" => "Financing Support", "Tax and NI investigations" => "Tax Services", "Benchmarking" => "Business Consulting & Support", "Business process improvements" => "Business Consulting & Support", "Corporate recovery" => "Insolvency and Arbitration", "Cost systems and control" => "Bookkeeping & Admin", "Data processing services" => "Bookkeeping & Admin", "Debt counselling" => "Financing Support", "Estate planning and executorship" => "Other", "Expert witness" => "Other", "Feasibility studies" => "Other", "Internal audit and systems security" => "Audit Services", "Trusteeship / Trust Administration" => "Other", "Bank loans and overdrafts (inc SFLGS)" => "Financing Support", "Business risk assessment" => "Business Consulting & Support", "Business plans (external and internal)" => "Business Consulting & Support", "Small scale equity issues" => "Financing Support", "Start-up Finance(inc using own funds)" => "Financing Support", "Divorce matrimonial" => "Insolvency and Arbitration", "Export finance planning and tax" => "Tax Services", "Grants and Finance (EU,government)" => "Financing Support", "Treasury" => "Other", "Establishing a business overseas" => "Formation / M&A", "Arbitration" => "Insolvency and Arbitration", "Environmental auditing" => "Audit Services", "Leasing and hire purchase" => "Other", "Asset Finance" => "Financing Support", "Annual Accounts" => "Annual Accounts", "Audit Services" => "Audit Services", "Business Advice" => "Business Consulting & Support", "Tax Services" => "Tax Services", "M&A/Transaction" => "Formation / M&A", "Bookkeeping" => "Bookkeeping & Admin", "Other" => "Other" } QUALIFICATIONS = ['ACCA']
class Uploader attr_accessor :bucket def initialize(bucket) @bucket = bucket end def upload_to_s3(path, key) s3_obj = bucket.objects[key] retries = 3 begin s3_obj.write(File.open(path, 'rb', :encoding => 'BINARY')) rescue => ex retries -= 1 if retries > 0 puts "ERROR during S3 upload: #{ex.inspect}. Retries: #{retries} left" retry else # oh well, we tried... raise end end end end
FactoryGirl.define do factory :opendata_part_mypage_login, class: Opendata::Part::MypageLogin, traits: [:cms_part] do transient do node nil end route "opendata/mypage_login" filename { node.blank? ? "#{name}.part.html" : "#{node.filename}/#{name}.part.html" } end factory :opendata_part_dataset, class: Opendata::Part::Dataset, traits: [:cms_part] do transient do node nil end route "opendata/dataset" filename { node.blank? ? "#{name}.part.html" : "#{node.filename}/#{name}.part.html" } end factory :opendata_part_dataset_group, class: Opendata::Part::DatasetGroup, traits: [:cms_part] do transient do node nil end route "opendata/dataset_group" filename { node.blank? ? "#{name}.part.html" : "#{node.filename}/#{name}.part.html" } end factory :opendata_part_app, class: Opendata::Part::App, traits: [:cms_part] do transient do node nil end route "opendata/app" filename { node.blank? ? "#{name}.part.html" : "#{node.filename}/#{name}.part.html" } end factory :opendata_part_idea, class: Opendata::Part::Idea, traits: [:cms_part] do transient do node nil end route "opendata/idea" filename { node.blank? ? "#{name}.part.html" : "#{node.filename}/#{name}.part.html" } end end
class ContactDetail < ActiveRecord::Base validates_presence_of :address, :telephone, :fax, :email end
require 'ripper' require 'ripper_ruby_parser/syntax_error' module RipperRubyParser # Variant of Ripper's SexpBuilder parser class that inserts comments as # Sexps into the built parse tree. # # @api private class CommentingRipperParser < Ripper::SexpBuilder def initialize(*args) super @comment = nil @comment_stack = [] @in_symbol = false end def parse result = suppress_warnings { super } raise 'Ripper parse failed.' unless result Sexp.from_array(result) end def on_comment(tok) @comment ||= '' @comment += tok super end def on_kw(tok) case tok when 'class', 'def', 'module' unless @in_symbol @comment_stack.push [tok.to_sym, @comment] @comment = nil end end super end def on_module(*args) commentize(:module, super) end def on_class(*args) commentize(:class, super) end def on_sclass(*args) commentize(:class, super) end def on_def(*args) commentize(:def, super) end def on_defs(*args) commentize(:def, super) end def on_args_new [:args] end def on_args_add(list, elem) list << elem end def on_mlhs_new [:mlhs] end def on_mlhs_add(list, elem) if list.first == :mlhs list << elem else [:mlhs_add_post, list, elem] end end def on_mrhs_new [:mrhs] end def on_mrhs_add(list, elem) list << elem end def on_qsymbols_new [:qsymbols] end def on_qsymbols_add(list, elem) list << elem end def on_qwords_new [:qwords] end def on_qwords_add(list, elem) list << elem end def on_regexp_new [:regexp] end def on_regexp_add(list, elem) list << elem end def on_stmts_new [:stmts] end def on_stmts_add(list, elem) list << elem end def on_string_add(list, elem) list << elem end def on_symbols_new [:symbols] end def on_symbols_add(list, elem) list << elem end def on_word_new [:word] end def on_word_add(list, elem) list << elem end def on_words_new [:words] end def on_words_add(list, elem) list << elem end def on_xstring_new [:xstring] end def on_xstring_add(list, elem) list << elem end def on_op(token) @seen_space = false super end def on_sp(_token) @seen_space = true super end def on_int(_token) @space_before = @seen_space super end def on_float(_token) @space_before = @seen_space super end NUMBER_LITERAL_TYPES = [:@int, :@float].freeze def on_unary(op, value) if !@space_before && op == :-@ && NUMBER_LITERAL_TYPES.include?(value.first) type, literal, lines = value if literal[0] == '-' super else [type, "-#{literal}", lines] end else super end end def on_symbeg(*args) @in_symbol = true super end def on_symbol(*args) @in_symbol = false super end def on_embexpr_beg(*args) @in_symbol = false super end def on_dyna_symbol(*args) @in_symbol = false super end def on_parse_error(*args) raise SyntaxError, *args end def on_class_name_error(*args) raise SyntaxError, *args end def on_alias_error(*args) raise SyntaxError, *args end def on_assign_error(*args) raise SyntaxError, *args end def on_param_error(*args) raise SyntaxError, *args end private def commentize(_name, exp) _tok, comment = @comment_stack.pop @comment = nil [:comment, comment || '', exp] end def suppress_warnings old_verbose = $VERBOSE $VERBOSE = nil result = yield $VERBOSE = old_verbose result end end end
$:.push File.expand_path("lib", __dir__) # Maintain your gem's version: require "quilt_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |spec| spec.name = "quilt_rails" spec.version = Quilt::VERSION spec.authors = ["Mathew Allen"] spec.email = ["mathew.allen@shopify.com"] spec.homepage = "https://github.com/Shopify/quilt/tree/main/gems/quilt_rails" spec.summary = "A turn-key solution for integrating server-rendered React into your Rails app using Quilt libraries." spec.description = "A turn-key solution for integrating server-rendered React into your Rails app using Quilt libraries." spec.license = "MIT" spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] spec.metadata['allowed_push_host'] = 'https://rubygems.org' spec.add_dependency 'railties', '>= 3.2.0' spec.add_dependency 'activesupport', '>= 3.2.0' spec.add_dependency 'rails-reverse-proxy', '~> 0.9.0' spec.add_dependency 'statsd-instrument', '>= 2.8.0' spec.add_development_dependency 'rails', '>= 7.0' spec.add_development_dependency 'rubocop', '~> 1.28' spec.add_development_dependency 'rubocop-git', '~> 0.1.3' spec.add_development_dependency 'rubocop-shopify', '~> 2.5' end