text
stringlengths
10
2.61M
class ProgramsController < ApplicationController def new end def create @program = Program.new(program_params) @program.save redirect_to @program end def show @program = Program.find(params[:id]) @days_ago_s = ProgramsHelper.string_days_ago(@program.airing_date.to_time) end private def program_params params.require(:program).permit(:number, :title, :description, :airing_date) end end
class AddLegacyLtiUserIdIndex < ActiveRecord::Migration[6.1] def change add_index :users, :legacy_lti_user_id, unique: true end end
# Copyright 2012© MaestroDev. All rights reserved. require 'spec_helper' require 'v_sphere_worker' describe MaestroDev::Plugin::VSphereWorker, :provider => "vsphere" do let(:connection) { Fog::Compute.new( :provider => "vsphere", :vsphere_username => username, :vsphere_password => password, :vsphere_server => host) } let(:host) { "localhost" } let(:username) { 'root' } let(:password) { 'password' } let(:datacenter) { 'Solutions' } let(:template_path) { 'rhel64' } let(:vm_name) { 'new vm' } let(:destination_folder) { "newfolder" } before do subject.workitem = {"fields" => fields} subject.stub(:connect => connection) connection.reset_data end describe 'provision' do let(:fields) {{ "params" => {"command" => "provision"}, "host" => host, "username" => username, "password" => password, "datacenter" => datacenter, "template_path" => template_path, "destination_folder" => destination_folder, "name" => "xxx" }} context 'when provisioning a machine' do before { subject.provision } its(:error) { should be_nil } it { expect(subject.workitem[Maestro::MaestroWorker::OUTPUT_META]).to match( /Server 'xxx' #{uuid_regex} started with public ip '192.168.100.184' and private ip ''/) } it { expect(field('vsphere_ids').to_s).to match(/^\["#{uuid_regex}"\]$/) } end context 'when template does not exist' do before { subject.provision } let(:fields) { super().merge({"template_path" => "doesnotexist"}) } its(:error) { should eq("VM template 'doesnotexist': Could not find VM template") } end context 'when template fails to clone' do let(:fields) { super().merge({"template_path" => "another"}) } before do connection.should_receive(:vm_clone).with({ "datacenter" => datacenter, "name" => "xxx", "template_path" => "another", "dest_folder" => destination_folder, "poweron" => true, "wait" => false }).and_raise(RbVmomi::Fault.new("message", "fault")) subject.provision end # jruby and c-ruby raise different exception messages its(:error) { should match(%r[^Error cloning template 'another' as 'newfolder/xxx'.*[Ff]ault]) } end end describe 'deprovision' do let(:fields) {{ "params" => {"command" => "deprovision"}, "vsphere_host" => host, "vsphere_username" => username, "vsphere_password" => password, "vsphere_ids" => ids, "__context_outputs__" => context_outputs('vsphere', ids), }} let(:ids) { ['5029c440-85ee-c2a1-e9dd-b63e39364603', '502916a3-b42e-17c7-43ce-b3206e9524dc'] } context 'when machines have been created' do before do stubs = connection.servers.find_all {|s| fields["vsphere_ids"].include?(s.identity)} stubs.size.should == 2 servers = double("servers") connection.stub(:servers => servers) stubs.each do |s| servers.should_receive(:get).once.with(s.identity).and_return(s) s.stub(:ready? => false) s.should_not_receive(:stop) s.should_receive(:destroy).once end subject.deprovision end its(:error) { should be_nil } end context 'when machine is running' do let(:id) { '502916a3-b42e-17c7-43ce-b3206e9524dc' } let(:fields) { super().merge({"vsphere_ids" => [id]}) } before do stub = connection.servers.find {|s| id == s.identity} stub.should_not be_nil servers = double('servers') connection.stub(:servers => servers) servers.should_receive(:get).with(id).and_return(stub) stub.ready?.should be_true stub.should_receive(:destroy).once subject.deprovision end its(:error) { should be_nil } end end def uuid_regex "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" end end
require_relative './item_behavior' module Vault # "Conjured" items degrade in Quality twice as fast as normal items class Conjured < ItemBehavior def initialize(item) super(item) end def update_quality quality = item.sell_in < 0 ? 4 : 2 decrease_quality(quality) end end end
module ApplicationHelper def full_title page_title = "" base_title = I18n.t "helpers.application_helper.title" page_title.blank? ? base_title : page_title + " | " + base_title end def format_date datetime datetime.strftime I18n.t(".format_time") end def will_paginate_helper objects will_paginate(objects, renderer: WillPaginate::ActionView::Bootstrap4LinkRenderer, class: "justify-content-center mb-5") end end
class PigLatin def initialize(phrase) @words = phrase.split end def self.translate(word) PigLatin.new(word).translate end def translate @words.map do |word| case when word.start_with?('sch', 'thr') then apply_sch_thr(word) when word.start_with?('squ') then apply_squ(word) when word.start_with?('ye') then apply_consonants(word) when word.start_with?('qu', 'th', 'ch') then apply_qu(word) when word.start_with?('a', 'e', 'i', 'o', 'u', 'y', 'xr') then apply_vowels(word) else apply_consonants(word) end end.join(' ') end def apply_vowels(word) word + 'ay' end def apply_consonants(word) word = word[1..-1] + word[0] + 'ay' end def apply_qu(word) word = word[2..-1] + word[0..1] + 'ay' end def apply_squ(word) word = word[3..-1] + word[0..2] + 'ay' end def apply_sch_thr(word) word[3..-1] + word[0..2] + 'ay' end end
Gem::Specification.new do |s| s.name = 'apex' s.version = '0.0.1' s.summary = "Apex Light enable perse Apex code and convert like Java." s.description = "Apex Light enable perse Apex code and convert like Java." s.files = %w( lib/apex.rb lib/apex/class.rb lib/apex/methods_and_fields.rb README ) # Rakefile ) # s.add_dependency("ruby-growl", ">= 1.0.1") s.author = 'Ayumu AIZAWA' s.email = 'ayumu.aizawa@gmail.com' s.homepage = 'http://twitter.com/ayumin' s.rubyforge_project = 'apex' s.has_rdoc = true end
module SurveyBuilder class Answer < ActiveRecord::Base belongs_to :question belongs_to :user belongs_to :survey_response validates :question, :presence => true before_save :validate_answer def get_question_type question.type end def validate_answer question.validate_answer(self) end def to_param end end end
module Pawnee class Base module Roles def self.included(base) #:nodoc: base.extend ClassMethods end module ClassMethods # Assigns the role for this class def role(role_name) @role = role_name end def class_role @role.to_s end # Returns the recipe classes in order based on the Gemfile order def ordered_recipes return @ordered_recipes if @ordered_recipes names = Bundler.load.dependencies.map(&:name) # Setup a hash with the recipe name and the recipe class recipe_pool = recipes.dup.inject({}) {|memo,recipe| memo[recipe.gem_name] = recipe ; memo } # Go through the gems in the order they are in the Gemfile, then # add them to the ordered list @ordered_recipes = [] names.each do |name| if recipe_pool[name] @ordered_recipes << recipe_pool[name] recipe_pool.delete(name) end end # Add the remaining recipes (load them after everything else) @ordered_recipes += recipe_pool.values return @ordered_recipes end # Returns the list of classes that match the current list of roles # in the correct run order def recipe_classes_with_roles(roles) # Check to make sure some recipes have been added if ordered_recipes.size == 0 raise Thor::InvocationError, 'no recipes have been defined' end if (roles.is_a?(Array) && roles.size == 0) || roles == :all # Use all classes role_classes = ordered_recipes else # Remove classes that don't fit the roles being used role_classes = ordered_recipes.reject do |recipe_class| ![roles].flatten.map(&:to_s).include?(recipe_class.class_role) end end end # Invokes all recipes that implement the passed in role def invoke_roles(task_name, roles, options={}) role_classes = self.recipe_classes_with_roles(roles) # Run the taks on each role class role_classes.each do |recipe_class| # This class matches the role, so we should run it recipe = recipe_class.new([], options) task = recipe_class.tasks[task_name.to_s] recipe.invoke_task(task) # Copy back and updated options options = recipe.options end end end end end end
# -*- coding: utf-8 -*- require "benchmark" require "csv" module Drnbench module Publish class GradualRunner def initialize(params) @params = params @runner = Runner.new(:start_n_subscribers => @params[:start_n_subscribers], :n_publishings => @params[:n_publishings], :timeout => @params[:timeout], :subscribe_request => @params[:subscribe_request], :feed => @params[:feed], :engine_config => @params[:engine_config], :protocol_adapter_config => @params[:protocol_adapter_config]) end def run results = [] @params[:n_steps].times do |try_count| @runner.add_subscribers(@runner.n_subscribers) if try_count > 0 label = "#{@runner.n_subscribers} subscribers" percentage = nil result = Benchmark.bm do |benchmark| benchmark.report(label) do published_messages = @runner.run percentage = published_messages.size.to_f / @params[:n_publishings] * 100 end end puts "=> #{percentage} % feeds are notified" result = result.join("").strip.gsub(/[()]/, "").split(/\s+/) qps = @params[:n_publishings].to_f / result.last.to_f puts " (#{qps} queries per second)" results << [label, qps] end total_results = [ ["case", "qps"], ] total_results += results puts "" puts "Results (saved to #{@params[:output_path]}):" File.open(@params[:output_path], "w") do |file| total_results.each do |row| file.puts(CSV.generate_line(row)) puts row.join(",") end end end end end end
module Wordbot module CLI class Mutilator < Thor desc 'version', 'Print the version' def version puts "mutilator version %s" % [ VERSION ] end map %w(-v --version) => :version desc 'generate', 'Generated some mutilated text' def generate *words puts Wordbot::Bot.mutilate words.join ' ' end map %w(-g --generate) => :generate desc 'from_file', 'Generate mutilated text from a file' def from_file filename f = File.read filename puts Wordbot::Bot.mutilate f end desc 'tweet', 'Tweet the mutilated text' def tweet *words begin yaml = YAML.load File.open "#{ENV['HOME']}/.wordbotrc" rescue Errno::ENOENT puts "Config file #{ENV['HOME']}/.wordbotrc not found" exit 1 end client = Twitter::REST::Client.new do |config| config.consumer_key = yaml['twitter']['consumer']['key'] config.consumer_secret = yaml['twitter']['consumer']['secret'] config.access_token = yaml['twitter']['oauth']['token'] config.access_token_secret = yaml['twitter']['oauth']['secret'] end tweet = Wordbot::Bot.mutilate words.join ' ' client.update tweet end map %w(-t --tweet) => :tweet end end end
require 'rss/maker' module Feeds # Atom news feed generator. class NewsFeedGenerator # Generate atom feed for given news. # # @example Generate atom feed for given news # news = News.all # Feeds::NewsFeedGenerator.generate(news) # #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\" …" # # @param news [Array<News>] should be generate to an atom feed # @param options [Hash] to define feed preferences # @option opts [String] :author Feed author # @option opts [String] :about Feed about text # @option opts [String] :title Feed title # # @return [String] atom feed def self.generate(news, options: {}) atom_feed = build_feed(news, options) atom_feed.to_s end # Build atom feed object for given news. # # @example Generate atom feed object for given news # news = News.all # Feeds::NewsFeedGenerator.events(news) #=> #<RSS::Atom::Feed:0x007fbe057c218> # # @param news [Array<News>] to convert to an atom feed # @param options [Hash] to define feed preferences # @option opts [String] :author Feed author # @option opts [String] :about Feed about text # @option opts [String] :title Feed title # # @return [RSS::Atom::Feed] atom feed def self.build_feed(news, options) RSS::Maker.make('atom') do |feed| assign_feed_options(feed, options) # Create feed item for every news news.each do |news| feed.items.new_item do |item| assign_item_options(item, news) end end end end protected # Assign news options to an atom feed item. # # @param item [RSS::Maker::Atom::Feed::Items::Item] # @param news [News] object def self.assign_item_options(item, news) item.id = "tag:media.ccc.de,#{news.created_at.strftime('%Y-%m-%d')}:#{news.id}" item.updated = Time.now.utc.to_s item.title = news.title item.content.content = news.body item.content.type = 'html' item.published = news.created_at.utc item.updated = news.updated_at.utc item.link = Settings.frontend_url end # Assign options like a title or an author to an atom feed. # # @param feed [RSS::Maker::Atom::Feed] atom feed # @param options [Hash] options def self.assign_feed_options(feed, options) feed.channel.id = 'media.ccc.de,news' feed.channel.author = options[:author] feed.channel.updated = Time.now.utc.to_s feed.channel.about = options[:about] feed.channel.title = options[:title] feed.channel.link = options[:feed_url] feed.channel.icon = options[:icon] feed.channel.logo = options[:logo] # define feed link attributes feed.channel.links.first.rel = 'self' feed.channel.links.first.type = 'application/atom+xml' end end end
require 'config/environment' namespace :index do desc 'Index all records for search' task :all do t_start = Time.now puts "Starting to index at #{t_start}" Content.all.each{|c| Indexer.index(c) } t_end = Time.now puts "Completed indexing at #{t_end}" end end
# Problem # - write a method # - that takes an array, and two optional string arguments # - the array holds the elements to be joined together # - the first optional string argument represents a separator to be used between # all of the elements of the array, except when there are only two elements # - the second optional string argument represents a separator to be used # between the last two elements # - if the first string is not provided, ', ' will be used # - if the second string is not provided, ' or ' will be used # Examples # joinor([1, 2]) # => "1 or 2" # joinor([1, 2, 3]) # => "1, 2, or 3" # joinor([1, 2, 3], '; ') # => "1; 2; or 3" # joinor([1, 2, 3], ', ', 'and') # => "1, 2, and 3" # Data Structure # input: Array and two Strings # output: a String (a new object) # Algorithm # - first string is called sep_1 # - second string is called sep_2 # - initialize sep_last to sep_1 + sep_2 + " " # - join all but the last array element using sep_1. Store result in # all_but_last # - join all_but_last and array.last with sep_last as the separator # - return the resulting value # Code require 'pry' def joinor(array, sep_1 = ', ', sep_2 = 'or') return array.join(" #{sep_2} ") if array.size <= 2 all_but_last = array[0..-2].join(sep_1) sep_last = sep_1 + sep_2 + " " [all_but_last, array.last].join(sep_last) end puts joinor([1]) # => "1" puts joinor([1, 2]) # => "1 or 2" puts joinor([1, 2, 3]) # => "1, 2, or 3" puts joinor([1, 2, 3], '; ') # => "1; 2; or 3" puts joinor([1, 2, 3], ', ', 'and') # => "1, 2, and 3" # Analysis # - the above works, but now that I'm looking at this code the next day, it's # not immediately clear to me what's going on # - I tried to be clever, because a lot of the solutions at Launch School are # pretty short and still clear; I wanted to achieve something similar # - I might have gone too short and faux clever, though # - below is an approximation of the solution from LS, a much clearer way: def joinor(array, separator = ', ', word = 'or') case array.size when 0 then '' # Nothing to join, return empty string when 1 then array.first # Return the one element when 2 then array.join(" #{word} ") else array[-1] = "#{word} #{array.last}" # Prep last element array.join(separator) # Join all elements end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable mount_uploader :avatar, AvatarUploader has_many :comments, dependent: :destroy has_many :restaurants, through: :comments has_many :favorites, dependent: :destroy has_many :favorited_restaurants, through: :favorites, source: :restaurant has_many :likes, dependent: :destroy has_many :liked_restaurants, through: :likes, source: :restaurant has_many :follows, class_name: :Followship, dependent: :destroy has_many :followings, through: :follows has_many :followeds, class_name: :Followship, foreign_key: :following_id, dependent: :destroy has_many :followers, through: :followeds def admin? return self.role == "admin" end def following?(user) self.followings.include?(user) end end
class DotAtomVerifier def execute(local) [ ld1(local), ld2(local), ld3(local), ld4(local), ld5(local) ].all? end def ld1(local) except = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-/=?^_`{|}~." local.chars.to_a.all? {|c| except.include?(c) } end def ld2(local) !local.start_with?('.') end def ld3(local) !local.end_with?('.') end def ld4(local) !local.include?('..') end def ld5(local) local.size >= 1 end end
# frozen_string_literal: true module Admin # AdminController class AdminController < ::ApplicationController layout 'admin/layouts/application' before_action :authenticate_user! before_action :validate_permissions before_action :paginator_params before_action :set_setting before_action :can_multiple_destroy, only: [:destroy_multiple] before_action :tables_name before_action :attachments before_action :authorization before_action :history def root if current_user redirect_to dashboard_path else redirect_to new_user_session_path end end def paginator_params @search_field = model.search_field if listing? @query = params[:search] unless params[:search].blank? @current_page = params[:page] unless params[:page].blank? end def validate_permissions return if current_user.rol.eql?('keppler_admin') redirect_to not_authorized_path unless current_user.permissions? end private def attachments @attachments = YAML.load_file( "#{Rails.root}/config/attachments.yml" ) end def only_development redirect_to '/admin' if Rails.env.eql?('production') end def authorization table = model.to_s.tableize.underscore.to_sym return unless ActiveRecord::Base.connection.table_exists? table authorize model end def get_history(_object) history end def history @activities = PublicActivity::Activity.where( trackable_type: model.to_s ).order('created_at desc').limit(50) end def tables_name @models = ApplicationRecord.connection.tables.map do |model| model.capitalize.singularize.camelize end end # Get submit key to redirect, only [:create, :update] def redirect(object, commit) redirect_to( { action: (commit.key?('_save') ? :show : :new), id: (object.id if commit.key?('_save')) }, notice: actions_messages(object) ) end def redefine_ids(ids) ids.delete('[]').split(',').select do |id| id if model.exists? id end end # Check whether the user has permission to delete # each of the selected objects def can_multiple_destroy redefine_ids(params[:multiple_ids]).each do |id| authorize model.find(id) end end end end
=begin input: integers (three of them) output: string rules - Explicit rules - Write a program to determine whether a triangle is equilateral, isosceles or scalene - All sides must be of length >0 - The sum of any two sides must be greater than or equal to the third side problem domain - Equilateral triangle has all three sides same length - Isosceles has two sides of same length - Scalene has all sides of different lengths ALGORITHM - Check that none of the sides are equal to 0 - Remove duplicates - If one left, - this is equilateral - If two left, - Check that the sum of lengths of any two sides must be greater than or equal to the length of the third side - Sorting collection in ascending order - Take the first two elements and make sure their sum is >= longest side - this is isosceles - if three left, - Check that the sum of lengths of any two sides must be greater than or equal to the length of the third side - Sorting collection in ascending order - Take the first two elements and make sure their sum is >= longest side - Check that the sum of lengths of any two sides must be greater than or equal to the length of the third side - This is scalene =end class Triangle def initialize(int1, int2, int3) check_if_valid_lengths(int1, int2, int3) @sides = [int1, int2, int3] end def check_if_valid_lengths(int1, int2, int3) arr = [int1, int2, int3].sort raise ArgumentError if arr.any? { |num| num <= 0 } raise ArgumentError if arr[0..1].sum < arr.last end def kind number_of_unique_sides = @sides.uniq.size case number_of_unique_sides when 3 then "scalene" when 2 then "isosceles" when 1 then "equilateral" end end end
require 'spec_helper' describe Collins::Ipmi do subject { asset = Collins::Asset.from_json(CollinsFixture.full_asset(true)) asset.ipmi } it_behaves_like "flexible initializer", :id => 23, :address => "hello" it "#empty?" do subject.empty?.should be_false end it "#address" do subject.address.should == "10.80.97.234" end it "#asset_id" do subject.asset_id.should == 1455 end it "#gateway" do subject.gateway.should == "10.80.97.1" end it "#id" do subject.id.should == 1436 end it "#netmask" do subject.netmask.should == "255.255.255.0" end it "#password" do subject.password.should == "fizzbuzz12" end it "#username" do subject.username.should == "root" end end
module Scavenger module ViewHelpers def compressor @compressor ||= Scavenger::Compressor.new(Scavenger::Config.svg_directory) end def svg_sprite_sheet content_tag :svg, compressor.compress_dir.html_safe, style: "display:none;" end def svg(ref, options = {}) options[:class] = scavenger_symbol_class(ref) if options[:class].nil? content_tag :svg, "<use xlink:href=\"##{scavenger_symbol_ref(ref)}\"/>".html_safe, options end def scavenger_sprite_path asset_path File.basename(Scavenger::Config.sprite_path) end def scavenger_symbol_class(ref) "#{Scavenger::Config.class_prefix}#{ref.gsub('/', '--')}" end def scavenger_symbol_ref(ref) "#{Scavenger::Config.id_prefix}#{ref.gsub('/', '--')}" end end end ActiveSupport.on_load(:action_view) { include Scavenger::ViewHelpers }
# Build a student testing app. # The app should have a class of Student and the student should "login" # with their email and password before they can take a test. # The user should be able to take the test and receive feedback on answers. # Their score should be saved and printed at the end of the test. # If they score under 60 they should be prompted to take the test again. class Student def initialize(name, email, password) @name = name @email = email @password = password end def name @name end def email @email end def password @password end # def score # score = 0 # end # def correct_answer # score += 25 # end def login puts 'Please login. What\'s your email?' login_id = gets.chomp.downcase if login_id != @email puts 'Account not found.' login else login_id == @email puts 'Please enter your password.' pw = gets.chomp.downcase if pw != @password puts 'Access denied.' login else pw == @password puts "Welcome #{@name.capitalize}, you are now ready to take the test." puts 'There are four questions on the test. Each question is worth 25 points. All questions are true or false, please answer with T or F.' test1 end end end def test1 puts 'Question 1: Raleigh is the capital of North Carolina.' q1 = gets.chomp.downcase if q1 != 't' puts 'Incorrect. Raleigh is the capital of NC.' test2 elsif q1 == 't' puts 'Correct. 25 points.' # correct_answer test2 else puts 'Please answer with T or F.' test1 end end def test2 puts 'Question 2: The United States borders three oceans.' q2 = gets.chomp.downcase if q2 != 'f' puts 'Incorrect. Raleigh is the capital of NC.' test3 elsif q2 == 'f' puts 'Correct. 25 points.' # correct_answer test3 else puts 'Please answer with T or F.' test2 end end def test3 puts 'Question 3: Colorado is part of the United States.' q3 = gets.chomp.downcase if q3 != 't' puts 'Incorrect. Raleigh is the capital of NC.' test4 elsif q3 == 't' puts 'Correct. 25 points.' # correct_answer test4 else puts 'Please answer with T or F.' test3 end end def test4 puts 'Question 4: The United States has 50 states.' q4 = gets.chomp.downcase if q4 != 'f' puts 'Incorrect. Raleigh is the capital of NC.' test_complete elsif q4 == 'f' puts 'Correct. 25 points.' # correct_answer test_complete else puts 'Please answer with T or F.' test4 end end def test_complete puts "You have completed the test. You scored ." end end student_data = Student.new('robert', 'bob@abc.com', 'open') student_data.login
class CreateStories < ActiveRecord::Migration[5.2] def change create_table :stories do |t| t.string :title t.integer :theme t.string :difficulty t.string :enemy t.string :enemy_gender t.boolean :enemy_prefix t.references :character, foreign_key: true t.timestamps end end end
class Meeting < ApplicationRecord belongs_to :client belongs_to :user # before_save do # self.end_time = self.start_time.advance(hours: (self.duration_hours if attribute_present?("duration_hours")), minutes: (self.duration_minutes if attribute_present?("duration_minutes")) ) if attribute_present?("start_time") # end def store_range Rangex.create(start: self.start_time, finish: self.end_time) end def check_unavailable_dates Rangex.all.detect do |r| (self.start_time).between?(r.start, r.finish) || (self.end_time).between?(r.start, r.finish) || (r.start).between?(self.start_time, self.end_time) || (r.finish).between?(self.start_time, self.end_time) end end end
module Orocos class DefaultLoader < OroGen::Loaders::Aggregate # @return [Boolean] whether the types that get registered on {registry} # should be exported as Ruby constants attr_predicate :export_types? # The namespace in which the types should be exported if # {export_types?} returns true. It defaults to Types # # @return [Module] attr_reader :type_export_namespace def initialize @type_export_namespace = ::Types # We need recursive access lock @load_access_lock = Monitor.new super self.export_types = true end def export_types=(flag) if !export_types? && flag registry.export_to_ruby(type_export_namespace) do |type, exported_type| if type.name =~ /orogen_typekits/ # just ignore those elsif type <= Typelib::NumericType # using numeric is transparent in Typelib/Ruby elsif type.contains_opaques? # register the intermediate instead intermediate_type_for(type) elsif m_type?(type) # just ignore, they are registered as the opaque else exported_type end end @export_types = true elsif export_types? && !flag type_export_namespace.disable_registry_export @export_types = false end end def clear super OroGen::Loaders::RTT.setup_loader(self) if export_types? && registry type_export_namespace.reset_registry_export(registry) end end def register_project_model(project) super project.self_tasks.each_value do |task| task.each_extension do |ext| Orocos.load_extension_runtime_library(ext.name) end end end def task_model_from_name(name) @load_access_lock.synchronize do super end end end end
require 'rails_helper' RSpec.describe User, type: :model do it { should have_valid(:first_name).when('Link', 'Zelda') } it { should_not have_valid(:first_name).when(nil, '') } it { should have_valid(:last_name).when('Courage', 'Wisdom') } it { should_not have_valid(:last_name).when(nil, '') } it { should have_valid(:email).when('link@hyrulecastle.com', 'zelda@hyrulecastle.com') } it { should_not have_valid(:email).when(nil, '', 'lidns', 'hyrulecastle.com') } it { should have_valid(:role).when('member', 'admin') } it { should_not have_valid(:role).when(nil, '')} it 'has a matching password confirmation for the password' do user = User.new user.password = 'zelda1212' user.password_confirmation = 'imthehero1212' expect(user).to_not be_valid expect(user.errors[:password_confirmation]).to_not be_blank end end
class ChangeColumnAttr < ActiveRecord::Migration def change change_column :fees, :deleted, :boolean, :default => false change_column :users, :deleted, :boolean, :default => false change_column :addresscats, :deleted, :boolean, :default => false change_column :customers, :deleted, :boolean, :default => false end end
class User < ActiveRecord::Base before_save { self.email == email.downcase } before_create :create_remember_token validates :first_name, presence: true validates :last_name, presence: true, allow_blank: true validates :email, presence: true, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { minimum: 8 } validates :username, allow_blank: true, length: { in: 2..32, too_short: 'Username is too short.', too_long: 'Username is too long.' } has_many :orders has_many :items has_many :order_items, through: :items has_attached_file :avatar, styles: { :medium => "300x300#", :thumb => "100x100#" }, default_url: "/assets/medium/awesome.png" validates_attachment :avatar, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] } def full_name "#{first_name} #{last_name}" end has_secure_password def User.new_remember_token SecureRandom.urlsafe_base64 end def User.digest(token) Digest::SHA1.hexdigest(token.to_s) end def full_name "#{first_name} #{last_name}" end def name username || full_name end private def default_url "/assets/avatars" end def create_remember_token self.remember_token = User.digest(User.new_remember_token) end end
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper.rb')) class BlocksStoriesTest < ActionController::IntegrationTest story "Create a new block" do scenario "Try to create a new block with invalid data" do visit "/" click_button :submit assert_contain "Code can't be empty" assert_contain "New Block" end scenario "Create a new public block with valid data" do visit "/" fill_in :block_revision_attr_snippet, :with => "Testing public block" click_button :submit assert_contain "Block was successfully created." assert_contain "Revisions" assert_contain "Testing public block" end scenario "Create a new private block with valid data" do visit "/" fill_in :block_revision_attr_snippet, :with => "Testing private block" uncheck "block_shared" click_button :submit assert_contain "Block was successfully created." assert_contain "Testing private block" click_link "Blocks" assert_not_contain "Testing private block" end def teardown Block.delete_all end end story "Edit a block" do def setup @block = create_block(:revision_attr => { :snippet => "Just testing"}) end scenario "Given a block that I own, I want to change code of block" do visit "/blocks/#{@block.id}/edit" assert_contain "Just testing" fill_in :block_revision_attr_snippet, :with => "changing the code" click_button :submit assert_contain "Successfully updated block." assert_contain "changing the code" assert_contain "Revisions" assert_contain "Last" assert_contain "Revision 1" click_link "Revision 1" assert_have_no_selector "actions" end scenario "Given a block that I own, I want to change privacity of block" do visit "/blocks/#{@block.id}/edit" uncheck :block_shared click_button :submit assert_contain "Successfully updated block." visit "/blocks" assert_not_contain "prueba" end scenario "Given a block wich I not own, I cant edit it" do visit "/blocks/#{@block.id}" assert_contain "Just testing" assert_have_no_selector "edit_#{@block.id}" end def teardown Block.delete_all end end story "Delete a block" do scenario "Given a block wich I own, I want to delete it" do visit "/" fill_in :block_revision_attr_snippet, :with => "Just testing delete" click_button :submit assert_contain "Block was successfully created." @block = Block.last visit "/blocks" assert_contain "Just testing delete" click_link "delete_#{@block.id}" assert_contain "Successfully destroyed block." assert_not_contain "Just testing delete" end scenario "Given a block wich I not own, I cant delete it" do @block = create_block(:revision_attr => { :snippet => "Just testing delete"}) visit "/blocks" assert_contain "Just testing delete" assert_have_no_selector "delete_#{@block.id}" end def teardown Block.delete_all end end private def create_block(attributes={}) default = { :revision_attr => { :revision_number => 1, :snippet => "Test", :file_type_id => 1}, :shared => 1, :owner => 1, :last_revision => 1 }.merge(attributes) Block.create(default) end end
class Especialidad < ActiveRecord::Base has_many :medicos end
# class Micropost < ActiveRecord::Base belongs_to :user validates :content, length: { maximum: 140} validates :user_id, presence: true validate :user_is_not_exist_or_is_race private def user_is_not_exist_or_is_race if !User.ids.include?(user_id) || User.find(user_id).name == "race" errors.add(:user, 'user is not exist or can not be race') end end end
require 'rails_helper' def leave_review(thoughts, rating) visit '/restaurants' fill_in 'Thoughts', with: thoughts select rating, from: 'Rating' click_button 'Create Review' end describe 'writing reviews' do context 'a logged out user' do it 'should not see the review form' do visit '/restaurants' expect(page).not_to have_content "Review KFC" end end context 'a logged in user' do before do user = User.create(email: 'test@test.com', password: '12345678', password_confirmation: '12345678') user.restaurants.create(name: 'KFC', cuisine: 'Fast Food') login_as(user) end it 'should add the review of a resturant' do leave_review('Not great', 2) expect(page).to have_content 'Not great (★★☆☆☆)' end it 'should not be able to add multiple reviews' do leave_review('Not great', 2) leave_review('Really bad!', 1) expect(page).to have_content 'Not great (★★☆☆☆)' expect(page).not_to have_content 'Really bad! (★☆☆☆☆)' expect(page).to have_content 'You already left a review of this restaurant!' end end end describe 'average ratings' do before do user = User.create(email: 'test@test.com', password: '12345678', password_confirmation: '12345678') user.restaurants.create(name: 'KFC', cuisine: 'Fast Food') another_user = User.create(email: 'test2@test.com', password: '12345678', password_confirmation: '12345678') login_as(user) leave_review('Not great', 2) login_as(another_user) leave_review('Great', 4) end context 'two logged in user leave two reviews' do it 'the app calculates and displays the average ratings' do expect(page).to have_content 'Average rating: ★★★☆☆' end end end
class Venue < ActiveRecord::Base has_many :addresses has_many :gigs has_many :artists end
require 'spec_helper' describe "SimpleDBAdapter ActiveRecord with optimistic locking" do before :each do ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Base.establish_connection($config) ActiveRecord::Base.connection.create_domain($config[:domain_name]) end after :each do ActiveRecord::Base.connection.delete_domain($config[:domain_name]) end it "should be have not nil lock version value after save" do p = Person.new p.save p.reload p.lock_version.should_not be_nil end it "should change lock version value after sevarals saves" do p = Person.new p.save old_lock_version = p.lock_version p.login = "blabla" p.save p.reload p.lock_version.should_not == old_lock_version end it "should raise error when tried save model with non-actual values (changed another place and time)" do p = Person.new p.save p1 = Person.find p.id p1.login = "blabla" p.login = "bla" p1.save lambda {p.save!}.should raise_error(ActiveRecord::StaleObjectError) end it "should raise error when tried destroy item with changed state" do p = Person.new p.save p1 = Person.find p.id p1.login = "blabla" p1.save lambda {p.destroy}.should raise_error(ActiveRecord::StaleObjectError) end end
class User < ActiveRecord::Base has_many :invoices has_many :banks has_many :senders validates :email, presence: true, uniqueness: true validates :password_digest, presence: true end
require 'test_helper' class Backend::ModelExtensions::ProviderTest < ActiveSupport::TestCase def setup @storage = Backend::Storage.instance @storage.flushdb end context "provider account" do subject { FactoryBot.create :provider_account } should "update backend default_service when set and saved" do service = subject.first_service! assert_nil subject.default_service_id subject.default_service_id = service.id Service.any_instance.expects(:update_backend_service) subject.save! assert_equal service, subject.default_service end end end
require 'spec_helper' describe 'Issue API' do describe 'GET /api/service/v1/issues' do before do @issues = create_list(:issue, 20) get '/api/service/v1/issues' end it 'should be a valid request' do expect(response.status).to eq 200 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable JSON' do expect(JSON.parse(response.body)).to be_true end it 'should return an array of issues' do expect(json['issues']).to be_a Array end it 'should return 20 issues' do expect(json['issues'].length).to eq 20 end it 'should have issue nodes' do expect(json['issues'][1]['issue']).not_to be_nil end end describe 'GET /api/service/v1/issues/:id' do before do @issue = create :full_issue get "/api/service/v1/issues/#{@issue.to_param}" end it 'should be a valid request' do expect(response.status).to eq 200 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable JSON' do expect(json).not_to be_nil end it 'should return the requested issue' do expect(json['issue']['subject']).to eq @issue.subject expect(json['issue']['description']).to eq @issue.description expect(json['issue']['author']).to eq @issue.account.handle expect(json['issue']['categories']).to match_array @issue.categories.map { |c| {"name" => c.name} } expect(json['issue']['comments']).to match_array @issue.comments.map { |c| {"comment" => c.comment, "commenter" => c.account.handle} } #expect(json['issue']['solutions']).to match_array @issue.solutions.map { # |s| {"solution" => s.solution, "technician" => s.account.handle, "comments" => s.comments.map { # |c| {"comment" => c.comment, "commenter" => c.account.handle} # }} #} end end describe 'POST /api/service/v1/issues' do before do @issue = attributes_for :issue_params post '/api/service/v1/issues', {issue: @issue} end it 'should return a valid response' do expect(response.status).to eq 201 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable json' do expect(json).not_to be_nil end it 'should return the created issue' do expect(json['issue']['subject']).to eq @issue[:subject] expect(json['issue']['description']).to eq @issue[:description] expect(json['issue']['author']).to eq Account.find(@issue[:account_id]).handle expect(json['issue']['categories']).to match_array @issue[:category_ids].map { |c| {"name" => Category.find(c).name} } end end describe 'PATCH /api/service/v1/issues/:id' do before do @issue = create :issue @description = Faker::Lorem.paragraph patch "/api/service/v1/issues/#{@issue.to_param}", {issue: {description: @description}} end it 'should return a valid response' do expect(response.status).to eq 200 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable json' do expect(json).not_to be_nil end it 'should return the updated issue' do expect(json['issue']['subject']).to eq @issue.subject expect(json['issue']['description']).to eq @description expect(json['issue']['author']).to eq @issue.account.handle expect(json['issue']['categories']).to match_array @issue.categories.map { |c| {"name" => c.name} } end end describe 'DELETE /api/service/v1/issues/:id' do before do @issue = create :issue delete "/api/service/v1/issues/#{@issue.to_param}" end it 'should return a valid response' do expect(response.status).to eq 200 end it 'should delete the requested issue from the db' do get "/api/service/v1/issues/#{@issue.to_param}" expect(response.status).to eq 400 end end describe 'PUT /api/service/v1/issues/:id/addCategory' do before do @issue = create :issue @category = create :category put "/api/service/v1/issues/#{@issue.to_param}/addCategory", {issue: {category_ids: [@category.to_param]}} end it 'should return a valid response' do expect(response.status).to eq 200 end it 'should add the group to the issue' do categories = Issue.find(@issue.id).categories expect(categories).to include @category end end describe 'PUT /api/service/v1/issues/:id/removeCategory' do before do @issue = create :issue @category = @issue.categories.first put "/api/service/v1/issues/#{@issue.to_param}/removeCategory", {issue: {category_ids: [@category.to_param]}} end it 'should return a valid response' do expect(response.status).to eq 200 end it 'should remove the group from the issue' do categories = Issue.find(@issue.id).categories expect(categories).not_to include @category end end describe 'GET /api/service/v1/issues/:id/comments' do before do @issue = create :full_issue get "/api/service/v1/issues/#{@issue.to_param}/comments" end it 'should be a valid request' do expect(response.status).to eq 200 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable JSON' do expect(json).not_to be_nil end it 'should return an array of comments' do expect(json['comments']).to match_array @issue.comments.map { |c| {"comment" => c.comment, "commenter" => c.account.handle} } end end describe 'POST /api/service/v1/issues/:id/comments' do before do @issue = create :issue @comment = attributes_for :comment_params post "/api/service/v1/issues/#{@issue.to_param}/comments", {comment: @comment} end it 'should return a valid response' do expect(response.status).to eq 201 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable json' do expect(json).not_to be_nil end it 'should return the created issue' do expect(json['comment']['comment']).to eq @comment[:comment] expect(json['comment']['commenter']).to eq Account.find(@comment[:account_id]).handle end end describe 'GET /api/service/v1/issues/:id/solutions' do before do @issue = create :full_issue get "/api/service/v1/issues/#{@issue.to_param}/solutions" end it 'should be a valid request' do expect(response.status).to eq 200 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable JSON' do expect(json).not_to be_nil end it 'should return an array of solutions' do #expect(json['solutions']).to eq(@issue.solutions.map { # |s| {"solution" => s.solution, "technician" => s.account.handle, "comments" => s.comments.map { # |c| {"comment" => c.comment, "commenter" => c.account.handle} }} #}) end end describe 'POST /api/service/v1/issues/:id/solutions' do before do @issue = create :issue @solution = attributes_for :solution_params post "/api/service/v1/issues/#{@issue.to_param}/solutions", {solution: @solution} end it 'should return a valid response' do expect(response.status).to eq 201 end it 'should return json' do expect(response.content_type).to eq 'application/json' end it 'should return parseable json' do expect(json).not_to be_nil end it 'should return the created issue' do expect(json['solution']['solution']).to eq @solution[:solution] expect(json['solution']['technician']).to eq Account.find(@solution[:account_id]).handle end end end
module Puffer module Inputs class Base attr_accessor :builder, :template, :field def self.render *args new(*args).render end def initialize builder, field @builder = builder @field = field @template = builder.instance_variable_get :@template end def render html.html_safe end def html <<-INPUT <div class="label"> #{label} <div class="field_error"> #{error} </div> </div> #{input} INPUT end def label builder.label field end def input builder.text_field field, field.input_options end def error builder.object.errors[field.name.to_sym].first end def method_missing method, *args, &block template.send method, *args, &block if template.respond_to? method end end end end
class ContributionValidator < ActiveModel::Validator def validate(record) record.errors[:content] << "Comment cannot be blank" unless content_not_blank_or_link_or_embedded_snippet?(record) # This is needed but currently screws up the rspec tests. Don't have time rewrite all the specs right now, so we'll disregard this validation. #record.errors[:conversation] << "does not match parent contribution's conversation" unless parent_contribution_belongs_to_conversation?(record) end def top_level_or_parent_present?(record) record.class!=TopLevelContribution && record.parent.blank? end def content_not_blank_or_link_or_embedded_snippet?(record) !record.content.blank? || [Link, EmbeddedSnippet].include?(record.class) end def parent_contribution_belongs_to_conversation?(record) record.parent.nil? || record.parent.conversation_id == record.conversation_id end end
class Admin::StripeAccountsController < ApplicationController layout "store_merchant_layout" before_action :authenticate_user! before_filter :verify_is_merchant def account if current_user.stripe_account_id.blank? redirect_to admin_stripe_accounts_new_stripe_account_path else Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] begin user_account = current_user.stripe_account_id.to_s account = Stripe::Account.retrieve(user_account) @business_name = account.legal_entity.business_name unless account.legal_entity.business_name.nil? @entity_type = account.legal_entity.type unless account.legal_entity.type.nil? @account_first_name = account.legal_entity.first_name unless account.legal_entity.first_name.nil? @account_last_name = account.legal_entity.last_name unless account.legal_entity.last_name.nil? @dob_day = account.legal_entity.dob.day unless account.legal_entity.dob.day.nil? @dob_month = account.legal_entity.dob.month unless account.legal_entity.dob.month.nil? @dob_year = account.legal_entity.dob.year unless account.legal_entity.dob.year.nil? @address = account.legal_entity.address.line1 unless account.legal_entity.address.line1.nil? @city = account.legal_entity.address.city unless account.legal_entity.address.city.nil? @country = account.legal_entity.address.country unless account.legal_entity.address.country.nil? @state = account.legal_entity.address.state unless account.legal_entity.address.state.nil? @zip_postal = account.legal_entity.address.postal_code unless account.legal_entity.address.postal_code.nil? @tos_acceptance = account.tos_acceptance.date unless account.tos_acceptance.date.nil? # will be true or false, depending on if tax id submitted @business_tax_id_provided = account.legal_entity.business_tax_id_provided unless account.legal_entity.business_tax_id_provided.nil? # for U.S. accounts only, lest 4 digist of SSN. if @country == 'us' @ssn_last_4 = account.legal_entity.ssn_last_4_provided unless account.legal_entity.ssn_last_4_provided.nil? end # will be false if personal id number hasn't been provided. SIN for Canada and SSN for U.S. @personal_id_number_provided = account.legal_entity.personal_id_number_provided unless account.legal_entity.personal_id_number_provided.nil? @transfer_schedule_delay = account.transfer_schedule.delay_days unless account.transfer_schedule.delay_days.nil? @transfer_schedule_interval = account.transfer_schedule.interval unless account.transfer_schedule.interval.nil? # list of fields needed to require identity @fields_needed = account.verification.fields_needed # account status @charges_enabled = account.charges_enabled unless account.charges_enabled.nil? # whether automatic transfers are enable for this account. @transfers_enabled = account.transfers_enabled unless account.transfers_enabled.nil? # identity verification status, can be unverified, pending, or verified. @verification_status = account.legal_entity.verification.status @external_accounts = account.external_accounts.all(:object => "bank_account") unless account.external_accounts.nil? # the default currency for the account, help to determine delete permissions on external accounts @default_currency = account.default_currency unless account.default_currency.nil? rescue Stripe::StripeError => e flash[:error] = e.message end end end def update_banking Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] begin token = params[:stripeToken] user_account = current_user.stripe_account_id.to_s account = Stripe::Account.retrieve(user_account) account.external_accounts.create({:external_account => token}) redirect_to admin_account_path flash[:notice] = "You have successfully added a bank account!" rescue Stripe::StripeError => e redirect_to admin_account_path flash[:error] = e.message end end def delete_bank_account Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] begin user_account = current_user.stripe_account_id.to_s account = Stripe::Account.retrieve(user_account) account.external_accounts.retrieve(params[:bank_id]).delete redirect_to admin_account_path flash[:notice] = "Successfully removed bank account!" rescue Stripe::StripeError => e redirect_to admin_account_path flash[:error] = e.message end end def edit_banking Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] begin token = params[:stripeToken] user_account = current_user.stripe_account_id.to_s account = Stripe::Account.retrieve(user_account) params[:default_for_currency] ? default_for_currency = true : default_for_currency = false account.external_accounts.create({:external_account => token, :default_for_currency => default_for_currency}) redirect_to admin_account_path flash[:notice] = "You have successfully added a bank account!" rescue Stripe::StripeError => e redirect_to admin_account_path flash[:error] = e.message end end def update_company_details Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] begin account_user = current_user.stripe_account_id account = Stripe::Account.retrieve(account_user) account.legal_entity.business_name = params[:business_name] account.legal_entity.type = params[:type] account.legal_entity.business_tax_id = params[:business_number] account.legal_entity.address.line1 = params[:address] account.legal_entity.address.city = params[:city] account.legal_entity.address.state = params[:state] account.legal_entity.address.country = params[:country] account.legal_entity.address.postal_code = params[:zip_postal] if params[:tos] account.tos_acceptance.date = Time.now.to_i account.tos_acceptance.ip = request.remote_ip end account.save redirect_to admin_account_path flash[:notice] = "Successfully updated!" rescue Stripe::StripeError => e redirect_to admin_account_path flash[:error] = e.message end end def update_personal_id_number Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] begin user_account = current_user.stripe_account_id account = Stripe::Account.retrieve(user_account) account.legal_entity.personal_id_number = params[:stripeToken] account.save redirect_to admin_account_path flash[:notice] = "Successfully updated!" rescue Stripe::StripeError => e redirect_to admin_account_path flash[:error] = e.message end end def verify_account Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] begin user_account = current_user.stripe_account_id account = Stripe::Account.retrieve(user_account) account.legal_entity.first_name = params[:first_name] unless params[:first_name].blank? account.legal_entity.last_name = params[:last_name] unless params[:last_name].blank? account.legal_entity.dob.day = params[:dob_day] unless params[:dob_day].blank? account.legal_entity.dob.month = params[:dob_month] unless params[:dob_month].blank? account.legal_entity.dob.year = params[:dob_year] unless params[:dob_year].blank? account.save redirect_to admin_account_path flash[:notice] = "Successfully updated!" rescue Stripe::StripeError => e redirect_to admin_account_path flash[:error] = e.message end end def verify_password if current_user.valid_password?(params[:password]) redirect_to admin_account_path else redirect_to admin_products_path flash[:error] = "Your password was incorrect." end end def new_stripe_account end def create_account Stripe.api_key = ENV['PLATFORM_SECRET_KEY'] # use this action to create account and add the account id to the current_user's account user = User.find(current_user.id) if params[:tos] begin country = santize_country(user.country) currency = select_currency(user.country) account = Stripe::Account.create( { :country => country, :managed => true, :default_currency => currency, } ) user.update_attribute(:stripe_account_id, account.id) if terms_acceptance = params[:tos] update_stripe_attributes(user) redirect_to admin_products_path flash[:notice] = "Congratulations! You have successfully created your Merchant Account!" else redirect_to admin_stripe_accounts_new_stripe_account_path flash[:error] = "You must agree to the terms of service before continuing." end rescue Stripe::StripeError => e redirect_to admin_stripe_accounts_new_stripe_account_path flash[:error] = e.message end else redirect_to admin_stripe_accounts_new_stripe_account_path flash[:error] = "You must accept the terms and conditions before continuing." end end private def update_stripe_attributes(user) user_account = user.stripe_account_id.to_s account = Stripe::Account.retrieve(user_account) account.legal_entity.type = "company" account.legal_entity.business_name = user.merchant_name.to_s unless user.merchant_name.blank? account.legal_entity.first_name = user.contact_first_name.to_s unless user.contact_first_name.blank? account.legal_entity.last_name = user.contact_last_name.to_s unless user.contact_last_name.blank? account.legal_entity.address.line1 = user.street_address.to_s unless user.street_address.blank? account.legal_entity.address.city = user.city.to_s unless user.city.blank? country = santize_country(user.country) unless user.country.blank? account.legal_entity.address.country = country unless user.country.blank? state = sanitize_prov_state(user.state_prov) unless user.state_prov.blank? account.legal_entity.address.state = state.to_s unless user.state_prov.blank? account.legal_entity.address.postal_code = user.zip_postal.to_s unless user.zip_postal.blank? account.tos_acceptance.date = Time.now.to_i account.tos_acceptance.ip = request.remote_ip account.save end def verify_is_merchant (current_user.nil?) ? redirect_to(shop_path) : (redirect_to(shop_path) unless current_user.merchant?) end def santize_country(country) case country when 'United States of America' 'US' when 'Canada' 'CA' end end def select_currency(country) case country when 'United States of America' 'usd' when 'Canada' 'cad' end end def sanitize_prov_state(prov_state) case prov_state when 'Alberta' 'AB' when 'British Columbia' 'BC' when 'Manitoba' 'MB' when 'New Brunswick' 'NB' when 'Newfoundland and Labrador' 'NL' when 'Northwest Territories' 'NT' when 'Nova Scotia' 'NS' when 'Nunavut' 'NU' when 'Ontario' 'ON' when 'Prince Edward Island' 'PE' when 'Quebec' 'QC' when 'Saskatchewan' 'SK' when 'Yukon' 'YT' when 'Alabama' 'AL' when 'Alaska' 'AK' when 'Arizona' 'AZ' when 'Arkansas' 'AR' when 'California' 'CA' when 'Colorado' 'CO' when 'Connecticut' 'CT' when 'Delaware' 'DE' when 'Florida' 'FL' when 'Georgia' 'GA' when 'Hawaii' 'HI' when 'Idaho' 'ID' when 'Illinois' 'IL' when 'Indiana' 'IN' when 'Iowa' 'IA' when 'Kansas' 'KS' when 'Kentucky' 'KY' when 'Louisiana' 'LA' when 'Maine' 'ME' when 'Maryland' 'MD' when 'Massachusetts' 'MA' when 'Michigan' 'MI' when 'Minnesota' 'MN' when 'Mississippi' 'MS' when 'Missouri' 'MO' when 'Montana' 'MT' when 'Nebraska' 'NE' when 'Nevada' 'NV' when 'New Hampshire' 'NH' when 'New Jersey' 'NJ' when 'New Mexico' 'NM' when 'New York' 'NY' when 'North Carolina' 'NC' when 'North Dakota' 'ND' when 'Ohio' 'OH' when 'Oklahoma' 'OK' when 'Oregon' 'OR' when 'Pennsylvania' 'PA' when 'Rhode Island' 'RI' when 'South Carolina' 'SC' when 'South Dakota' 'SD' when 'Tennessee' 'TN' when 'Texas' 'TX' when 'Utah' 'UT' when 'Vermont' 'VT' when 'Virginia' 'VA' when 'Washington' 'WA' when 'Washington, D.C.' 'DC' when 'West Virginia' 'WV' when 'Wisconsin' 'WI' when 'Wyoming' 'WY' else end end end
class PerShowPatronNotes < ActiveRecord::Migration def self.up add_column :shows, :patron_notes, :string, :null => true, :default => nil end def self.down remove_column :shows, :patron_notes end end
# == Schema Information # # Table name: lessons # # id :integer not null, primary key # name :string # title :string # overview :text # created_at :datetime not null # updated_at :datetime not null # course_id :integer # permalink :string # bbs :string # discourse_topic_id :integer # project :string # discourse_qa_topic_id :integer # class Lesson < ActiveRecord::Base include EventLogging #validates :name, uniqueness: { case_sensitive: false, scope: :course_id, # message: "should have uniq name per course" } validates :name, presence: true validates_uniqueness_of :name, scope: :course_id validates_uniqueness_of :permalink, scope: :course_id belongs_to :course def content @content ||= Content.new(self.course, self) end def to_param self.permalink end def position course.content.position_of_lesson(self.name) end def name=(name) self.permalink = name.parameterize super(name) end def project_repo_name_for(user) "#{user.github_username}/sike-#{self.course.name}-#{self.project}" end def project_repo_url_for(user) "https://github.com/#{project_repo_name_for(user)}" end def discourse_checkin_topic_url "http://#{ENV["DISCOURSE_HOST"]}/t/#{self.discourse_topic_id}" end def discourse_qa_topic_url "http://#{ENV["DISCOURSE_HOST"]}/t/#{self.discourse_qa_topic_id}" end def create_checkin_topic return if self.discourse_topic_id title = "Lesson #{self.position} 打卡 - #{self.title}" raw = "课程打卡在这里" category = "#{self.course.name} FAQ" api = Checkin::DiscourseAPI.new result = api.create_topic(title, raw, category) self.update(discourse_topic_id: result['topic_id']) end def create_qa_topic return if self.discourse_qa_topic_id title = "Lesson #{self.position} FAQ - #{self.title}" raw = "课程有问题在这里提问。" category = "#{self.course.name} FAQ" api = Checkin::DiscourseAPI.new result = api.create_topic(title, raw, category) self.update_attribute :discourse_qa_topic_id, result['topic_id'] rescue RestClient::Exception => e p e.response.headers puts e.response.to_str log_event("discourse.checkin-fail", { lesson_id: self.id, body: e.response.to_str.force_encoding("UTF-8") }) raise e end end
class Bid < ActiveRecord::Base belongs_to :admin belongs_to :order #validates :admin_id, presence: true validates :order_id, presence: true validates :price, numericality: {greater_than: 0} validates :subtotal, numericality: {greater_than: 0} validates :message, presence: true validates :pay_schedule, presence: true delegate :user, to: :order delegate :name, to: :admin, prefix: true delegate :storefront, to: :admin, allow_nil: true end
require 'test_helper' class AdminformsControllerTest < ActionController::TestCase setup do @adminform = adminforms(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:adminforms) end test "should get new" do get :new assert_response :success end test "should create adminform" do assert_difference('Adminform.count') do post :create, adminform: { php_project: @adminform.php_project, php_title: @adminform.php_title, redmine_project: @adminform.redmine_project, redmine_title: @adminform.redmine_title } end assert_redirected_to adminform_path(assigns(:adminform)) end test "should show adminform" do get :show, id: @adminform assert_response :success end test "should get edit" do get :edit, id: @adminform assert_response :success end test "should update adminform" do put :update, id: @adminform, adminform: { php_project: @adminform.php_project, php_title: @adminform.php_title, redmine_project: @adminform.redmine_project, redmine_title: @adminform.redmine_title } assert_redirected_to adminform_path(assigns(:adminform)) end test "should destroy adminform" do assert_difference('Adminform.count', -1) do delete :destroy, id: @adminform end assert_redirected_to adminforms_path end end
class GroupUsersController < ApplicationController before_action :authenticate_user def create params['user_id'] = current_user.id @group_user = GroupUser.new(group_users_params) if @group_user.save redirect_to group_url(@group_user.group_id), notice: 'グループに参加しました' else redirect_to groups_url, notice: 'グループに参加できません' end end def destroy @group_user = GroupUser.find_by(group_id: params[:id], user_id: current_user.id) if @group_user.destroy redirect_to groups_url, notice: 'グループを離脱しました' else redirect_to groups_url, notice: 'グループを離脱できません' end end private def group_users_params params.permit(:group_id, :user_id) end end
module Svpply class Collection attr_reader :id, :title, :masthead, :masthead_height, :masthead_width, :preview_type, :preview_image, :representative_item_id, :representative_item_width, :representative_item_height, :products_count, :is_private, :is_wishlist, :date_created, :date_updated, :creator, :svpply_url def self.find(id) new(Client.get_response("/collections/#{id}.json")["collection"]) end def self.products(id, attrs=nil) ProductCollection.new(Client.get_response("/collections/#{id}/products.json", attrs)).products end def initialize(hash) @id = hash["id"] @title = hash["title"] @masthead = hash["masthead"] @masthead_height = hash["masthead_height"] @masthead_width = hash["masthead_width"] @preview_type = hash["preview_type"] @preview_image = hash["preview_image"] @representative_item_id = hash["representative_item_id"] @representative_item_height = hash["representative_item_height"] @representative_item_width = hash["representative_item_width"] @products_count = hash["products_count"] @is_private = hash["is_private"] @is_wishlist = hash["is_wishlist"] @date_created = hash["date_created"] @date_updated = hash["date_updated"] @creator = hash["creator"] @creator["portrait"] = @creator["avatar"].gsub("avatars", "portraits") @svpply_url = "https://svpply.com/collections/#{@id}" end end end
require 'rails_helper' RSpec.describe Post, type: :model do describe 'validation' do it { should validate_presence_of(:title) } it { should validate_presence_of(:body) } it { should belong_to(:user) } it { should validate_uniqueness_of(:title).with_message("You can't have two posts with the same title.") } end it 'convert markdown to html' do post = Post.new(body: 'One **beautiful** post that *just* created!') expect(post.content_html).to include('<strong>beautiful</strong>') expect(post.content_html).to include('<em>just</em>') end end
ActiveAdmin.setup do |config| config.site_title = "Vidhata Cranes" config.site_title_link = "/" ## Rails url helpers do not work here config.authentication_method = :authenticate_admin_user! config.current_user_method = :current_admin_user config.logout_link_path = :destroy_admin_user_session_path config.batch_actions = true end
# inspired by https://github.com/thoughtbot/paperclip/blob/master/MIGRATING.md class ConvertToActiveStorage < ActiveRecord::Migration[5.2] def up ActiveRecord::Base.transaction do source_by_blob_key = {} blobs = [] Source.all.each do |src| next if src.document.path.blank? key = SecureRandom.uuid blobs << { key: key, filename: src.document_file_name, content_type: src.document_content_type, metadata: '{}', byte_size: src.document_file_size, checksum: Digest::MD5.base64digest(File.read(src.document.path)), created_at: src.updated_at.iso8601 } source_by_blob_key[key] = src end ActiveStorage::Blob.import(blobs, validate: false) attachments = [] ActiveStorage::Blob.all.each do |blob| src = source_by_blob_key[blob.key] attachments << { name: 'document', record_type: 'Source', record_id: src.id, blob_id: blob.id, created_at: src.updated_at.iso8601 } end ActiveStorage::Attachment.import(attachments, validate: false) end end def down raise ActiveRecord::IrreversibleMigration end end
# Admin Messages Controller: JSON response through Active Model Serializers class Api::V1::AdminMessagesController < MasterApiController respond_to :json def index render json: AdminMessage.all end def show render json: adminMessage end def create render json: AdminMessage.create(adminMessage_params) end def update render json: adminMessage.update(adminMessage_params) end def destroy render json: adminMessage.destroy end private def adminMessage AdminMessage.find(params[:id]) end def adminMessage_params params.require(:data).require(:attributes).permit(:message, :title) end end
class AddTakePartInToUser < ActiveRecord::Migration[5.0] def change add_column :users, :take_part_in, :boolean, default: :true end end
class BatchSerializer include JSONAPI::Serializer attributes :reference, :purchase_channel has_many :orders end
class Transaction < ActiveRecord::Base belongs_to :invoice def self.random all.shuffle.first end def self.find_invoices(params) find(params[:transaction_id]).invoice end def self.find_transactions(params) where(invoice_id: params[:invoice_id]) end def self.find_all_by_id(params) where(id: params[:id]) end def self.find_all_by_invoice_id(params) where(invoice_id: params[:invoice_id]) end def self.find_all_by_credit_card_number(params) where(credit_card_number: params[:credit_card_number]) end def self.find_all_by_created_at(params) where(created_at: params[:created_at]) end def self.find_all_by_updated_at(params) where(updated_at: params[:updated_at]) end def self.find_all_by_result(params) where('LOWER(result) = ?', params[:result]) end def self.find_by_id(params) find(params[:id]) end def self.find_by_invoice_id(params) find_by(invoice_id: params[:invoice_id]) end def self.find_by_credit_card_number(params) find_by(credit_card_number: params[:credit_card_number]) end def self.find_by_created_at(params) find_by(created_at: params[:created_at]) end def self.find_by_updated_at(params) find_by(updated_at: params[:updated_at]) end def self.find_by_result(params) find_by('LOWER(result) = ?', params[:result].downcase) end end
module AttendancesHelper def attendance_state(attendance) # 受け取ったAttendanceオブジェクトが当日と一致するか評価します。 if Date.current == attendance.worked_on return '出勤' if attendance.started_at.nil? return '退勤' if attendance.started_at.present? && attendance.finished_at.nil? end # どれにも当てはまらなかった場合はfalseを返します。 return false end # 出勤時間と退勤時間を受け取り、在社時間を計算して返します。 def working_times(start, finish) format("%.2f", (((finish - start) / 60) / 60.0)) end # 出勤時間を15分単位にして返します(切り上げ) def started_at_to_15_in_minutes(started_at) case started_at.min when 0..14 started_at.change(min: 15) when 15..29 started_at.change(min: 30) when 30..44 started_at.change(min: 45) when 45..59 started_at.change(hour: started_at.hour + 1, min: 0) end end # 退勤時間を15分単位にして返します(切り捨て) def finished_at_to_15_in_minutes(finished_at) case finished_at.min when 0..14 finished_at.change(min: 0) when 15..29 finished_at.change(min: 15) when 30..44 finished_at.change(min: 30) when 45..59 finished_at.change(min: 45) end end end
# typed: true # frozen_string_literal: true module Packwerk # extracts a possible constant reference from a given AST node class ReferenceExtractor extend T::Sig sig do params( context_provider: Packwerk::ConstantDiscovery, constant_name_inspectors: T::Array[Packwerk::ConstantNameInspector], root_node: ::AST::Node, root_path: String, ).void end def initialize( context_provider:, constant_name_inspectors:, root_node:, root_path: ) @context_provider = context_provider @constant_name_inspectors = constant_name_inspectors @root_path = root_path @local_constant_definitions = ParsedConstantDefinitions.new(root_node: root_node) end def reference_from_node(node, ancestors:, file_path:) constant_name = T.let(nil, T.nilable(String)) @constant_name_inspectors.each do |inspector| constant_name = inspector.constant_name_from_node(node, ancestors: ancestors) break if constant_name end reference_from_constant(constant_name, node: node, ancestors: ancestors, file_path: file_path) if constant_name end private def reference_from_constant(constant_name, node:, ancestors:, file_path:) namespace_path = Node.enclosing_namespace_path(node, ancestors: ancestors) return if local_reference?(constant_name, Node.name_location(node), namespace_path) constant = @context_provider.context_for( constant_name, current_namespace_path: namespace_path ) return if constant&.package.nil? relative_path = Pathname.new(file_path) .relative_path_from(@root_path).to_s source_package = @context_provider.package_from_path(relative_path) return if source_package == constant.package Reference.new(source_package, relative_path, constant) end def local_reference?(constant_name, name_location, namespace_path) @local_constant_definitions.local_reference?( constant_name, location: name_location, namespace_path: namespace_path ) end end end
class CreateAppointments < ActiveRecord::Migration def change create_table :appointments do |t| t.integer :sender_id t.integer :recipient_id t.string :place t.string :latitude t.string :longitude t.string :placetype t.datetime :date t.timestamps end add_index :appointments, :sender_id add_index :appointments, :recipient_id end end
class Online_Party # @return [Array<Online_Actor>] attr_reader :actors def initialize(data) json_party = base64_decode data party = JSON.decode json_party @actors = party.map{ |member_data| Online_Actor.new(member_data) } end end class Online_Actor < Game_Actor def setup(data) actor_id = data['id'] super(actor_id) @level = data['level'] @maxhp_plus = data['mhp_p'] @maxmp_plus = data['mmp_p'] @atk_plus = data['atk_p'] @def_plus = data['def_p'] @spi_plus = data['spi_p'] @agi_plus = data['agi_p'] @skills = data['skills'] @learned_passives = data['passives'] @weapon_id = data['weapons'].first @equip_type = data['equip_types'].map{|t|t.to_sym} recover_all end end
module Entities class UserSearchResultEntity < Grape::Entity expose :id expose :first_name expose :last_name expose :email end end
class AddVerificationCodeToPhones < ActiveRecord::Migration def change add_column :phones, :verification_code, 'CHAR(4)' end end
# coding: utf-8 # frozen_string_literal: true # This script installs the various files from the dotzshrc "ecosystem". require 'fileutils' $stdout.puts 'Installing zshrc aliases…' home_dirname = ENV.fetch('HOME') symlink_sources = File.expand_path('symlinks/dot.*', __dir__) Dir.glob(symlink_sources).each do |source_filename| basename = File.basename(source_filename) next if basename == '.' next if basename == '..' target_basename = basename.to_s.sub("dot.", ".") # Create a symlink in HOME directory to source_filename target_name = File.join(home_dirname, target_basename) $stdout.puts "\t#{target_name} ->\n\t\t#{source_filename}" FileUtils.ln_sf(source_filename, target_name) end $stdout.puts 'Finished installing zshrc aliases…' $stdout.puts 'Installing bin aliases…' bin_sources = File.expand_path('bin/*', __dir__) FileUtils.mkdir_p(File.join(home_dirname, 'bin')) Dir.glob(bin_sources).each do |source_filename| # Create a symlink in HOME directory to source_filename target_name = File.join(home_dirname, 'bin', File.basename(source_filename)) $stdout.puts "\t#{target_name} ->\n\t\t#{source_filename}" FileUtils.ln_sf(source_filename, target_name) end $stdout.puts 'Finished installing bin aliases…' ["emacs", "emacsclient"].each do |basename| source_filename = File.join("/opt/homebrew/opt/emacs-plus@29/bin/", basename) target_name = File.join(home_dirname, 'bin', File.basename(basename)) $stdout.puts "\t#{target_name} ->\n\t\t#{source_filename}" FileUtils.ln_sf(source_filename, target_name) end $stdout.puts 'Installing emacs.d symlinks…' FileUtils.mkdir_p(File.join(home_dirname, '.emacs.d')) [ File.expand_path(File.join(home_dirname, 'git/dotemacs/emacs.d/.*')), # Hidden files File.expand_path(File.join(home_dirname, 'git/dotemacs/emacs.d/*')), # Non-hidden files ].each do |glob| Dir.glob(glob).each do |source_filename| basename = File.basename(source_filename) next if basename == '.' next if basename == '..' target_basename = basename.to_s # Create a symlink in HOME directory to source_filename target_name = File.join(home_dirname, '.emacs.d', target_basename) $stdout.puts "\t#{target_name} ->\n\t\t#{source_filename}" FileUtils.ln_sf(source_filename, target_name) end end $stdout.puts 'Finished installing .emacs.d aliases…' platform = `uname`.strip.downcase if platform =~ /darwin/ $stdout.puts "Installing karabiner elements (you'll need to enable them)" target_filename = File.join(home_dirname, ".config/karabiner/assets/complex_modifications/modifications.json") FileUtils.mkdir_p(File.basename(target_filename)) source_filename = File.join(home_dirname, "git/dotzshrc/karabiner/modifications.json") FileUtils.cp(source_filename, target_filename) $stdout.puts "Installing global git config for darwin" unless system("git config --system --get credential.helper") system("git config --system --add credential.helper osxkeychain") end unless system("git config --system --get interactive.diffFilter") system("git config --system --add interactive.diffFilter \"`brew --prefix git`/share/git-core/contrib/diff-highlight/diff-highlight\"") end unless system("git config --system --get core.pager") system("git config --system --add core.pager \"`brew --prefix git`/share/git-core/contrib/diff-highlight/diff-highlight | less -F -X\"") end system("source $HOME/git/dotzshrc/configs/darwin-defaults.zsh") elsif platform =~ /linux/ $stdout.puts "Installing global git config for gnu-linux" $stdout.puts(%(Run "sudo git config --system --add credential.helper /usr/lib/git-core/git-credential-libsecret")) $stdout.puts(%(Run "sudo git config --system --add interactive.diffFilter /usr/share/git/diff-highlight/diff-highlight")) $stdout.puts(%(Run "sudo git config --system --add core.pager \"/usr/share/git/diff-highlight/diff-highlight | less -F -X\"")) end
require 'rubygems' require 'openssl' require 'cgi' require 'base64' require 'openssl' require 'net/http' require 'net/https' require 'typhoeus' require 'json' TCA_ENV = 'production' unless defined?(TCA_ENV) THE_CITY_ADMIN_PATH = 'https://api.onthecity.org' unless defined?(THE_CITY_ADMIN_PATH) THE_CITY_ADMIN_API_VERSION = 'application/vnd.thecity.admin.v1+json' unless defined?(THE_CITY_ADMIN_API_VERSION) # The path to the lib directory. THECITY_LIB_DIR = File.dirname(__FILE__) # The path to the storage directory that will be used for caching data to disk. THECITY_STORAGE_DIR = File.dirname(__FILE__) + '/../storage/' require File.dirname(__FILE__) + '/auto_load.rb' require File.dirname(__FILE__) + '/common.rb' # This class is meant to be a wrapper TheCity Admin API (OnTheCity.org). module TheCityAdmin class AdminApi class << self attr_reader :api_key, :api_token end def self.connect(admin_api_key, admin_api_token) raise TheCityExceptions::UnableToConnectToTheCity.new('Key and Token cannot be nil.') if admin_api_key.nil? or admin_api_token.nil? @api_key = admin_api_key @api_token = admin_api_token end end end
require 'rails_helper' describe ItemsController, type: :controller do describe 'GET #index' do it "populates an array of tweets ordered by created_at DESC" do end it "renders the :index template" do end end end
class AddFieldsToSpreeUsers < ActiveRecord::Migration[5.2] def change add_column :spree_users, :name, :string add_column :spree_users, :phone, :string end end
require 'rails_helper' RSpec.describe SynchronizeIssueWorker, type: :worker do let(:issue) { create(:existing_issue, updated_at: 30.days.ago) } before do allow(Github::Issues).to receive(:synchronize).and_return(true) issue end describe '.perform' do it 'synchronizes the issue' do expect(Github::Issues).to receive(:synchronize).with(issue) described_class.new.perform(issue.id) end end end
class CreateConditionsPeople < ActiveRecord::Migration def change create_table :conditions_people, :id => false do |t| t.references :condition, :null => false t.references :person, :null => false end end end
require 'spec_helper' describe CampRegistration do context "with no fields shown" do before(:each) do @camp_registration = CampRegistration.new(:registration_form_id => Factory(:registration_form).id) end it "should not save the camp registration without a name" do @camp_registration.name = "" @camp_registration.save.should be_true, "camp registration not saved without name" end it "should not save the camp registration without an email" do @camp_registration.email = "" @camp_registration.save.should be_true, "camp registration not saved without email" end it "should not save the camp registration without an age" do @camp_registration.age = "" @camp_registration.save.should be_true, "camp registration not saved without age" end it "should not save the camp registration without a position" do @camp_registration.position = "" @camp_registration.save.should be_true, "camp registration not saved without position" end it "should not save the camp registration without a school" do @camp_registration.school = "" @camp_registration.save.should be_true, "camp registration not saved without school" end it "should not save the camp registration without a phone number" do @camp_registration.phone = "" @camp_registration.save.should be_true, "camp registration not saved without a phone number" end it "should not save the camp registration without a street address" do @camp_registration.street_address = "" @camp_registration.save.should be_true, "camp registration not saved without a street address" end it "should not save the camp registration without a city" do @camp_registration.city = "" @camp_registration.save.should be_true, "camp registration not saved without a city" end it "should not save the camp registration without a state" do @camp_registration.state = "" @camp_registration.save.should be_true, "camp registration not saved without a state" end it "should not save the camp registration without a zip code" do @camp_registration.zip = "" @camp_registration.save.should be_true, "camp registration not saved without a zip code" end it "should not save the camp registration without a grade" do @camp_registration.grade = "" @camp_registration.save.should be_true, "camp registration not saved without a grade" end it "should not save the camp registration without years of experience indicated" do @camp_registration.yrs_of_exp = "" @camp_registration.save.should be_true, "camp registration not saved without years of experience indicated" end it "should not save the camp registration without an explanation of how they found the company" do @camp_registration.finding_resolute = "" @camp_registration.save.should be_true, "camp registration not saved without an explanation of how they found the company" end end context "with all fields shown" do before(:each) do @registration_form = Factory(:registration_form) @camp_registration = CampRegistration.new(:registration_form_id => @registration_form.id) end it "should not save the camp registration without a name" do @registration_form.update_attribute(:name, true) @camp_registration.name = "" @camp_registration.save.should_not be_true, "camp registration saved without name" end it "should not save the camp registration without an email" do @registration_form.update_attribute(:email, true) @camp_registration.email = "" @camp_registration.save.should_not be_true, "camp registration saved without email" end it "should not save the camp registration without an age" do @registration_form.update_attribute(:age, true) @camp_registration.age = "" @camp_registration.save.should_not be_true, "camp registration saved without age" end it "should not save the camp registration without a position" do @registration_form.update_attribute(:position, true) @camp_registration.position = "" @camp_registration.save.should_not be_true, "camp registration saved without position" end it "should not save the camp registration without a school" do @registration_form.update_attribute(:school, true) @camp_registration.school = "" @camp_registration.save.should_not be_true, "camp registration saved without school" end it "should not save the camp registration if the email address is not in the proper format" do @registration_form.update_attribute(:email, true) @camp_registration.email = "9h0(H#09" @camp_registration.save.should_not be_true, "camp registration saved without proper email format" end it "should not save the camp registration if age is greater than two numbers" do @registration_form.update_attribute(:age, true) @camp_registration.age = 100 @camp_registration.save.should_not be_true, "camp registration saved with age greater than 99" end it "should not save the camp registration if age is not a number" do @registration_form.update_attribute(:age, true) @camp_registration.age = "Test" @camp_registration.save.should_not be_true, "camp registration saved with age not an integer" end it "should not save the camp registration without a phone number" do @registration_form.update_attribute(:phone, true) @camp_registration.phone = "" @camp_registration.save.should_not be_true, "camp registration saved without a phone number" end it "should not save the camp registration with a malformed phone number" do @registration_form.update_attribute(:phone, true) @camp_registration.phone = "02jf092jf" @camp_registration.save.should_not be_true, "camp registration saved with a malformed phone number" end it "should not save the camp registration with a phone number longer than 10 characters" do @registration_form.update_attribute(:phone, true) @camp_registration.phone = "48304839203" @camp_registration.save.should_not be_true, "camp registration saved with a phone number longer than 10 characters" end it "should not save the camp registration without a street address" do @registration_form.update_attribute(:address, true) @camp_registration.street_address = "" @camp_registration.save.should_not be_true, "camp registration saved without a street address" end it "should not save the camp registration without a city" do @registration_form.update_attribute(:address, true) @camp_registration.city = "" @camp_registration.save.should_not be_true, "camp registration saved without a city" end it "should not save the camp registration without a state" do @registration_form.update_attribute(:address, true) @camp_registration.state = "" @camp_registration.save.should_not be_true, "camp registration saved without a state" end it "should not save the camp registration without a zip code" do @registration_form.update_attribute(:address, true) @camp_registration.zip = "" @camp_registration.save.should_not be_true, "camp registration saved without a zip code" end it "should not save the camp registration without a grade" do @registration_form.update_attribute(:grade, true) @camp_registration.grade = "" @camp_registration.save.should_not be_true, "camp registration saved without a grade" end it "should not save the camp registration without years of experience indicated" do @registration_form.update_attribute(:yrs_of_exp, true) @camp_registration.yrs_of_exp = "" @camp_registration.save.should_not be_true, "camp registration saved without years of experience indicated" end it "should not save the camp registration without an explanation of how they found the company" do @registration_form.update_attribute(:finding_resolute, true) @camp_registration.finding_resolute = "" @camp_registration.save.should_not be_true, "camp registration saved without an explanation of how they found the company" end end describe ".format_for_save" do let(:camp_registration) {Factory.attributes_for(:camp_registration, :position => {:attack => "Attack", :goalie => "Goalie", :middle => "Middle", :defense => "Defense"})} it "comma separates selected position checkboxes into one field" do result = CampRegistration.format_for_save(camp_registration) %w[Attack Goalie Middle Defense].each do |position| result[:position].should include position end end end describe "#registration_form" do let(:registration_form) {Factory(:registration_form)} let(:camp_registration) {Factory(:camp_registration, :registration_form_id => registration_form.id)} it "returns a registration form" do camp_registration.registration_form.should be_a(RegistrationForm) end it "returns the camp registration's registration form instance" do camp_registration.registration_form.should == registration_form end end end
class AddAssociationToShifts < ActiveRecord::Migration[5.2] def change add_reference :shifts, :assignment, foreign_key: true end end
class NotesController < ApplicationController load_and_authorize_resource only: [:edit, :show, :update] def index end def new @user = User.new @note = @user.notes.build end def create if current_user @user = User.find(current_user.id) note = @user.notes.create(content: params[:note][:content]) note.visible_to = params[:note][:visible_to] if !params[:note][:visible_to].empty? note.readers << current_user if current_user redirect_to '/' else redirect_to '/' end end def show end def edit end def update @note = Note.find(params[:id]) @note.update(note_params) redirect_to '/' end def destroy end private def note_params params.require(:note).permit(:content, :visible_to, :user_id) end def current_user User.find_by(id: session[:user_id]) end end
# # Cookbook Name:: blockheads_server # Recipe:: mac_os_x # CHECKSUM = '170eb3a5489ea7b3a9332fbaf444e143ab0eb2423a381ce668948ca33a6c4a11' remote_file "#{Chef::Config[:file_cache_path]}/BlockheadsServer.zip" do source "http://theblockheads.net/share/BlockheadsServer.zip" #checksum "#{CHECKSUM}" notifies :run, 'execute[unzip-bserver]' end execute 'unzip-bserver' do command "unzip #{Chef::Config[:file_cache_path]}/BlockheadsServer.zip -d /Applications" action :nothing end
class CreateIntroductions < ActiveRecord::Migration[6.0] def change create_table :introductions do |t| t.bigint :users_id, null: false, foreign_key: true t.bigint :boards_id, null: false, foreign_key: true t.text :content,null: false t.integer :category_id,null: false t.boolean :permission t.timestamps end end end
class RemoveTableGalleryAlbumsTags < ActiveRecord::Migration def change drop_table :albums_tags end end
#!/usr/bin/env ruby # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example creates a user role in a given DCM account. # # To get the account ID, run get_all_userprofiles.rb. To get the parent user # role ID, run get_user_roles.rb. require_relative '../dfareporting_utils' require 'securerandom' def create_user_role(profile_id, account_id, parent_role_id) # Authenticate and initialize API service. service = DfareportingUtils.initialize_service # Create a new user role resource to insert. user_role = DfareportingUtils::API_NAMESPACE::UserRole.new( account_id: account_id, name: format('Example User Role #%s', SecureRandom.hex(3)), parent_user_role_id: parent_role_id ) # Insert the user role. result = service.insert_user_role(profile_id, user_role) # Display results. puts format('Created user role with ID %d and name "%s".', result.id, result.name) end if $PROGRAM_NAME == __FILE__ # Retrieve command line arguments. args = DfareportingUtils.parse_arguments(ARGV, :profile_id, :account_id, :parent_role_id) create_user_role(args[:profile_id], args[:account_id], args[:parent_role_id]) end
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers setup do @user = users(:taro) @other_user = users(:jiro) sign_in(@user) end test "should get index" do get users_url assert_response :success end test "should show user" do get user_url(@user) assert_response :success end test "should get edit" do get edit_user_url(@user) assert_response :success end test "should update user" do picture = fixture_file_upload('test/fixtures/rails.png', 'image/png') patch user_url(@user), params: { user: { name: @user.name, profile: @user.profile, avatar: picture } } assert_redirected_to user_url(@user) end test "should destroy user" do assert_difference('User.count', -1) do delete user_url(@user) end assert_redirected_to users_url end #Admin関連のテスト test "should not allow the admin attribute to be edited via the web" do #web経由でAdmin属性の変更を許可しない sign_in(@other_user) assert_not @other_user.admin? patch user_path(@other_user), params: { user: {password: @other_user.password, password_confirmation: @other_user.password_confirmation, admin: true}} assert_not @other_user.reload.admin? end test "should redirect destroy when not logged in" do #ログインしないでuserを削除はリダイレクトtoログイン delete destroy_user_session_path(@user) assert_no_difference "User.count" do delete user_path(@user) end assert_redirected_to new_user_session_path end test "should redirect destroy when logged in as a non-admin" do #Adminじゃないでuserを削除はリダイレクトtoルートpath sign_in(@other_user) assert_no_difference 'User.count' do delete user_path(@user) end assert_redirected_to root_path end #User profileに関するテスト test "should redirect to index when wrong user edit user profile" do #違うuserがプロフをeditするとリダイレクト sign_in(@other_user) get edit_user_path(@user) assert_not flash.empty? assert_redirected_to users_path end test "should redirect to index when wrong user update user profile" do #違うuserがプロフをupdateするとリダイレクト sign_in(@other_user) patch user_path(@user), params: { user: { name: @user.name, profile: @user.profile}} assert_not flash.empty? assert_redirected_to users_path end end
class ServicePrice < ActiveRecord::Base validates :price, :service_id, :role_id, presence: true validates :service, uniqueness: { scope: :role_id }, presence: true belongs_to :service belongs_to :role delegate :name, :description, to: :service, prefix: true end
class Owner < ApplicationRecord has_many :dogs validates :name, presence: true, length: {minimum: 2} end
#encoding: utf-8 module Restfuls class Dianbos < Grape::API #version 'v1', :using => :path format :json helpers DianboHelper resource 'dianbo' do desc '创建一个新的奇遇点拨接口' params do requires :session_key,type: String,desc: '会话key' requires :type,type: Integer,desc: '点拨类型id' end get "/create_new_dianbo" do create_new_dianbo end post "/create_new_dianbo" do create_new_dianbo end desc '使用点拨接口' params do requires :session_key,type: String,desc: '会话key' requires :id,type: Integer,desc: '点拨id' end get "/use_dianbo" do use_dianbo end post "/use_dianbo" do use_dianbo end desc '获取未使用点拨接口' params do requires :session_key,type: String,desc: '会话key' end get "/get_unused_dianbos" do get_unused_dianbos end post "/get_unused_dianbos" do get_unused_dianbos end desc '删除点拨接口' params do requires :session_key,type: String,desc: '会话key' requires :id,type: Integer,desc: '点拨id' end get "/delete_dianbo" do delete_dianbo end post "/delete_dianbo" do delete_dianbo end end end end
class UserGame < ActiveRecord::Base class << self def unplayed_games(user) games = user_games_from_steam(user.uid) games.select { |g| g['playtime_forever'] == 0 } end private def user_games_from_steam(uid) steam_addr = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/' resp = HTTPClient.get steam_addr, { key: ENV['STEAM_API_KEY'], steamid: uid, format: 'json', include_appinfo: 1 } JSON.parse(resp.body)['response']['games'] end end end
module VersatileRJS class Proxy module Jquery class EachProxy < VersatileRJS::Proxy::EachProxy def initialize(page) super add_statement(ActiveSupport::JSON::Variable.new("var #{variable_name} = $(#{tmp_variable_name})")) end def tmp_variable_name @tmp_variable_name ||= "_tmp" + variable_name end def statement_prefix(statement) loop_variable_name = "_loop" + variable_name "$.each(function(#{loop_variable_name}, #{tmp_variable_name}){" end def statement_suffix(statement) "})" end end end end end
class HiLo attr_reader :lower attr_reader :upper def initialize(lower, upper) @lower = lower @upper = upper @number = rand(upper-lower) + lower end def guess(num) case num <=> @number when -1 puts "too low..." when 1 puts "too high..." else puts "found it!" end end end
#!/usr/bin/env ruby require 'fileutils' ############################## # # Standard Compile Script # # Supported compilers: # gcc, g++, and fpc. # ############################## def talk(str='') if ENV['TALKATIVE']!=nil puts str end if ENV['GRADER_LOGGING']!=nil log_fname = ENV['GRADER_LOGGING'] fp = File.open(log_fname,"a") fp.puts("run: #{Time.new.strftime("%H:%M")} #{str}") fp.close end end C_COMPILER = "/usr/bin/gcc" CPLUSPLUS_COMPILER = "/usr/bin/g++" PASCAL_COMPILER = "/usr/bin/fpc" C_OPTIONS = "-O2 -s -static -std=c99 -DCONTEST -lm -Wall" CPLUSPLUS_OPTIONS = "-O2 -s -static -DCONTEST -lm -Wall" PASCAL_OPTIONS = "-O1 -XS -dCONTEST" # Check for the correct number of arguments. Otherwise, print usage. if ARGV.length == 0 or ARGV.length > 4 puts "Usage: compile <language> [<source-file>] [<output-file>] [<message-file>]" puts puts "<source-file> is defaulted to \"source\"." puts "<output-file> is defaulted to \"a.out\"." puts "<message-file> is defaulted to \"compiler_message\"." puts exit(127) end PARAMS = { :source_file => [1,'source'], :output_file => [2,'a.out'], :message_file => [3,'compiler_message'] } params = {} params[:prog_lang] = ARGV[0] PARAMS.each_key do |param_name| index, default = PARAMS[param_name] if ARGV.length > index params[param_name] = ARGV[index] else params[param_name] = default end talk "#{param_name}: #{params[param_name]}" end # Remove any remaining output files or message files. if FileTest.exists? params[:output_file] FileUtils.rm(params[:output_file]) end if FileTest.exists? params[:message_file] FileUtils.rm(params[:message_file]) end # Check if the source file exists before attempt compiling. if !FileTest.exists? params[:source_file] talk("ERROR: The source file does not exist!") open(params[:message_file],"w") do |f| f.puts "ERROR: The source file did not exist." end exit(127) end if params[:prog_lang]=='cpp' params[:prog_lang] = 'c++' end # Compile. case params[:prog_lang] when "c" command = "#{C_COMPILER} #{params[:source_file]} -o #{params[:output_file]} #{C_OPTIONS} 2> #{params[:message_file]}" system(command) when "c++" command = "#{CPLUSPLUS_COMPILER} #{params[:source_file]} -o #{params[:output_file]} #{CPLUSPLUS_OPTIONS} 2> #{params[:message_file]}" system(command) when "pas" command = "#{PASCAL_COMPILER} #{params[:source_file]} -ooutpas #{PASCAL_OPTIONS} > #{params[:message_file]}" system(command) FileUtils.mv("output", params[:output_file]) else talk("ERROR: Invalid language specified!") open(params[:message_file],"w") do |f| f.puts "ERROR: Invalid language specified!" end exit(127) end # Report success or failure. if FileTest.exists? params[:output_file] talk "Compilation was successful!" else talk "ERROR: Something was wrong during the compilation!" end
class CreateConferences < ActiveRecord::Migration def self.up create_table :conferences do |t| t.string :name t.text :description t.datetime :start_time t.datetime :end_time t.string :room t.references :category t.float :fee t.integer :currency_id t.integer :parent_conference_id t.timestamps end end def self.down drop_table :conferences end end
require 'spec_helper' feature "Visitor makes payment", { vcr: true, js: true } do background do visit new_payment_path end scenario "valid card number", driver: :selenium do pay_with_credit_card('4242424242424242') page.should have_content 'Thank you for your generous support' end scenario "invalid card number" do pay_with_credit_card('4000000000000069') page.should have_content 'Your card has expired' end scenario "declined card" do pay_with_credit_card('4000000000000002') page.should have_content 'Your card was declined' end end def pay_with_credit_card(card_number) fill_in 'Credit Card Number', with: card_number fill_in 'Security Code', with: '123' select '3 - March', from: 'date_month' select '2017', from: 'date_year' click_button 'Submit Payment' end
class AddEthnicityToProfile < ActiveRecord::Migration[5.0] def change add_column :profiles, :aspirations, :string add_column :profiles, :identity, :string end end
class Movie < ActiveRecord::Base validates :name, presence: true, uniqueness: true validates :synopsis, presence: true end
class Airport < ApplicationRecord has_many :departing_flights, class_name: "Flight", foreign_key: "departure_airport_id" has_many :arriving_flights, class_name: "Flight", foreign_key: "destination_airport_id" validates :code, presence: true validates :location, presence: true end
class AddDesignerToIdeas < ActiveRecord::Migration def change add_column :ideas, :designer, :integer end end
require 'json' require 'httparty' module RegisteredDomains module NameCom # Get the list of registered domains for an account from name.com # Returns an array of domain names. class Domains attr_reader :domains def initialize(user, api_key) @auth = {username: user, password: api_key} @domains = get end def get url = "https://api.name.com/v4/domains" response = HTTParty.get(url, basic_auth: @auth) response.success? resp = JSON.parse(response) # Handle some known error messages rather than falling through and getting NoMethodError for nils if resp.has_key?('message') if resp['message'] == 'Unauthenticated' raise "Failed to authenticate to #{url}" elsif resp['message'] == 'Permission Denied' raise "#{resp['message']}: #{resp['details']}" else raise resp['message'] end end resp['domains'].map {|d| d['domainName']} end end end end
UserDisconnectLoginAccountMutation = GraphQL::Relay::Mutation.define do name 'UserDisconnectLoginAccount' input_field :provider, !types.String input_field :uid, !types.String return_field :success, types.Boolean return_field :user, UserType resolve -> (_root, inputs, _ctx) { user = User.current if user.nil? raise ActiveRecord::RecordNotFound else user.disconnect_login_account(inputs[:provider], inputs[:uid]) { success: true, user: User.current } end } end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require 'json' unless defined?(JSON) module ActiveSupport module JSON ParseError = ::JSON::ParserError unless const_defined?(:ParseError) module Backends module JSONGem extend self # Converts a JSON string into a Ruby object. def decode(json) data = ::JSON.parse(json) if ActiveSupport.parse_json_times convert_dates_from(data) else data end end private def convert_dates_from(data) case data when DATE_REGEX DateTime.parse(data) when Array data.map! { |d| convert_dates_from(d) } when Hash data.each do |key, value| data[key] = convert_dates_from(value) end else data end end end end end end
module HealthInspector module Checklists class Cookbook < Struct.new(:name, :path, :server_version, :local_version) def git_repo? self.path && File.exist?("#{self.path}/.git") end end class CookbookCheck < Struct.new(:cookbook) include Check end class CheckLocalCopyExists < CookbookCheck def check failure( "exists on chef server but not locally" ) if cookbook.path.nil? end end class CheckServerCopyExists < CookbookCheck def check failure( "exists locally but not on chef server" ) if cookbook.server_version.nil? end end class CheckVersionsAreTheSame < CookbookCheck def check if cookbook.local_version && cookbook.server_version && cookbook.local_version != cookbook.server_version failure "chef server has #{cookbook.server_version} but local version is #{cookbook.local_version}" end end end class CheckUncommittedChanges < CookbookCheck def check if cookbook.git_repo? result = `cd #{cookbook.path} && git status -s` unless result.empty? failure "Uncommitted changes:\n#{result.chomp}" end end end end class CheckCommitsNotPushedToRemote < CookbookCheck def check if cookbook.git_repo? result = `cd #{cookbook.path} && git status` if result =~ /Your branch is ahead of (.+)/ failure "ahead of #{$1}" end end end end class Cookbooks < Base def self.run(context) new(context).run end def initialize(context) @context = context end def run banner "Inspecting cookbooks" cookbooks.each do |cookbook| failures = cookbook_checks.map { |c| c.new(cookbook).run_check }.compact if failures.empty? print_success(cookbook.name) else print_failures(cookbook.name, failures) end end end def cookbooks server_cookbooks = cookbooks_on_server local_cookbooks = cookbooks_in_repo all_cookbook_names = ( server_cookbooks.keys + local_cookbooks.keys ).uniq.sort all_cookbook_names.map do |name| Cookbook.new.tap do |cookbook| cookbook.name = name cookbook.path = cookbook_path(name) cookbook.server_version = server_cookbooks[name] cookbook.local_version = local_cookbooks[name] end end end def cookbooks_on_server JSON.parse( @context.knife_command("cookbook list -Fj") ).inject({}) do |hsh, c| name, version = c.split hsh[name] = version hsh end end def cookbooks_in_repo @context.cookbook_path. map { |path| Dir["#{path}/*"] }. flatten. select { |path| File.exists?("#{path}/metadata.rb") }. inject({}) do |hsh, path| name = File.basename(path) version = (`grep '^version' #{path}/metadata.rb`).split.last[1...-1] hsh[name] = version hsh end end def cookbook_path(name) path = @context.cookbook_path.find { |f| File.exist?("#{f}/#{name}") } path ? File.join(path, name) : nil end def cookbook_checks [ CheckLocalCopyExists, CheckServerCopyExists, CheckVersionsAreTheSame, CheckUncommittedChanges, CheckCommitsNotPushedToRemote ] end end end end
require 'test_helper' class TeamsLayoutTest < ActionDispatch::IntegrationTest test "layout links" do get root_path assert_template 'teams/viewteams' assert_select "a[href=?]", root_path, count: 0 assert_select "a[href=?]", addteam_path, count: 1 end end
class User < ActiveRecord::Base has_secure_password has_many :user_events has_many :comments, dependent: :destroy has_many :events, :through => :user_events has_many :events, dependent: :destroy EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i validates :first_name, :last_name, length: { minimum: 2 } validates :email, format: { with: EMAIL_REGEX }, uniqueness: true validates :location, :state, presence: true validates :password, length: { minimum: 8 }, on: :create end
class CreateFileRecords < ActiveRecord::Migration[5.2] def change create_table :file_records do |t| t.string :timing t.string :class_name t.string :slot t.integer :uploaded_file_id t.integer :invigilator_id t.timestamps end end end
class Email < ActiveRecord::Base unloadable if Rails.env == 'development' belongs_to :contact validates_presence_of :address validates_length_of :address, :within => 6..100 #r@a.wk validates_format_of :address, :with => User::EMAIL_REGEX validates_uniqueness_of :address def kind=(k) k.blank? ? nil : super end end
class Question < ActiveRecord::Base attr_accessible :description, :hit_id, :title, :video_url, :status, :response_id has_many :responses after_create :make_hits def make_hits HitCreator.create(self) end def turkee_task Turkee::TurkeeTask.where(:hit_id => hit_id).first end def response_url if Rails.env == "development" "https://localhost:3000/responses/new" elsif Rails.env == "production" "https://eight-ball.herokuapp.com/responses/new" end end end
# frozen_string_literal: true class StudentsController < HtmlController include Pagy::Backend has_scope :exclude_deleted, only: :index, type: :boolean, default: true has_scope :exclude_empty, only: :performance, type: :boolean, default: true has_scope :table_order, only: :index, type: :hash has_scope :search, only: :index def index authorize Student @component = StudentComponents::StudentTable.new { |students| pagy apply_scopes(policy_scope(students)) } end def new authorize Student @student = populate_new_student end def create @student = Student.new student_params authorize @student return link_notice_and_redirect t(:student_created, name: @student.proper_name), new_student_path(group_id: @student.group_id), I18n.t(:create_another), details_student_path(@student) if @student.save render :new end def details @student = Student.includes(:profile_image, :group).find params.require(:id) authorize @student set_back_url_flash end def performance @student = Student.find params.require(:id) authorize @student @student_lessons_details_by_subject = apply_scopes(StudentLessonDetail).where(student_id: params[:id]).order(:date).all.group_by(&:subject_id) redirect_to action: :details if @student_lessons_details_by_subject.empty? @subjects = Subject.includes(:skills, :organization).where(id: @student_lessons_details_by_subject.keys) set_back_url_flash end def edit @student = Student.find params[:id] authorize @student @student.student_images.build end def update @student = Student.find params[:id] authorize @student return redirect_to details_student_path(@student) if update_student @student render :edit end def destroy @student = Student.find params.require :id authorize @student @student.deleted_at = Time.zone.now undo_notice_and_redirect t(:student_deleted, name: @student.proper_name), undelete_student_path, students_path if @student.save end def undelete @student = Student.find params.require :id authorize @student @student.deleted_at = nil notice_and_redirect t(:student_restored, name: @student.proper_name), request.referer || student_path(@student) if @student.save end private def student_params p = params.require(:student) p[:student_tags_attributes] = p.fetch(:tag_ids, []).map { |tag_id| { tag_id: tag_id } } p.delete :tag_ids p.permit(*Student.permitted_params) end def set_back_url_flash flash[:back_from_student] = flash[:back_from_student] || request.referer end def populate_new_student student = Student.new student.group = Group.find(new_params[:group_id]) if new_params[:group_id] student end def new_params params.permit :group_id end def update_student(student) p = student_params tag_ids = p[:student_tags_attributes].pluck(:tag_id) tags = Tag.where id: tag_ids p.delete :student_tags_attributes student.tags = tags student.update p end end
class ChangePaymentFrequencyInLoan < ActiveRecord::Migration[5.0] def change change_column :loans, :payment_frequency, :integer, default: 1, :null => false end end
require 'test_helper' class BagsControllerTest < ActionDispatch::IntegrationTest setup do @bag = bags(:one) end test "should get index" do get bags_url assert_response :success end test "should get new" do get new_bag_url assert_response :success end test "should create bag" do assert_difference('Bag.count') do post bags_url, params: { bag: { quantity: @bag.quantity, user_id: @bag.user_id } } end assert_redirected_to bag_url(Bag.last) end test "should show bag" do get bag_url(@bag) assert_response :success end test "should get edit" do get edit_bag_url(@bag) assert_response :success end test "should update bag" do patch bag_url(@bag), params: { bag: { quantity: @bag.quantity, user_id: @bag.user_id } } assert_redirected_to bag_url(@bag) end test "should destroy bag" do assert_difference('Bag.count', -1) do delete bag_url(@bag) end assert_redirected_to bags_url end end
require 'spec_helper' describe "apps/edit.html.erb" do before(:each) do pwd = 'cloud$' @user = User.create! :first_name => 'Dale', :last_name => 'Olds', :display_name => 'Dale O.', :password => pwd, :confirm_password => pwd, :email => 'olds@vmware.com' sign_in @user @app = App.create! :display_name => 'Transcoder', :creator => @user, :project => @user.personal_org.default_project, :url => "trans.cloudfoundry.com" @app = @app.reload end it "renders the edit app form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => apps_path(@app), :method => "post" do assert_select "input#app_display_name", :name => "app[display_name]" assert_select "input#app_framework", :name => "app[framework]" assert_select "input#app_runtime", :name => "app[runtime]" assert_select "input#app_description", :name => "app[description]" assert_select "input#app_url", :name => "app[url]" end end end
#!/usr/bin/ruby require "prime" need_primes = 10001 generator = Prime::EratosthenesGenerator.new count = 0 until count == need_primes do count += 1 new_prime = generator.next end puts new_prime
# Polisher Bodhi Operations # # Licensed under the MIT license # Copyright (C) 2013 Red Hat, Inc. require 'pkgwat' module Polisher class Bodhi def self.versions_for(name, &bl) # fedora pkgwat provides a frontend to bodhi updates = Pkgwat.get_updates("rubygem-#{name}", 'all', 'all') # TODO set timeout updates.reject! { |u| u['stable_version'] == 'None' && u['testing_version'] == "None" } versions = updates.collect { |u| u['stable_version'] } bl.call(:bodhi, name, versions) unless(bl.nil?) versions end end end