text
stringlengths
10
2.61M
require_relative('basket') class Discount def initialize(params) end def calculate(basket, running_total) raise 'Not implemented' end end class MultiBuyDiscount < Discount def initialize(params) super(params) @amount_needed = params[:amount_needed] @code = params[:code] @discount_price = params[:discount_price] end def calculate(basket, running_total) delta = @discount_price.to_f - basket.find(@code).price.to_f multi_buy_count = basket.find_and_count(@code) return multi_buy_count * delta if multi_buy_count >= @amount_needed 0.0 end end class PercentageDiscount < Discount def initialize(params) super(params) @price_threshold = params[:price_threshold] @discount_percent = params[:discount_percent] end def calculate(_basket, running_total) delta = - running_total * (@discount_percent.to_f / 100) return delta if running_total > @price_threshold 0.0 end end
require 'lib/racional.rb' require 'rspec' describe Racional do before :each do @rac = Racional end it "Debe existir un numerador" do @rac.new(1, 2).num.should == 1 end it "Debe existir un denominador" do @rac.new(1, 2).den.should == 2 end it "Debe de estar en su forma reducida" do @rac.new(2, 4).num.should == 1 @rac.new(7, -21).den.should == 3 end it "Se debe invocar al metodo num() para obtener el numerador" do @rac.new(2,4).respond_to?("num").should be_true end it "Se debe invocar al metodo den() para obtener el numerador" do @rac.new(1,2).respond_to?("den").should be_true end it "Se debe mostar por la consola la fraccion de la forma: a/b, donde a es el numerador y b el denominador" do @rac.new(1,2).to_s.should == "1/2" @rac.new(7,-21).to_s.should == "-1/3" end it "Se debe mostar por la consola la fraccion en formato flotante" do @rac.new(1,2).to_f.should == 1/2 @rac.new(-2,6).to_f.should == -1/3 end it "Se debe comparar si dos fracciones son iguales con ==" do @rac.new(1,2).should == @rac.new(2,4) @rac.new(-3,6).should == @rac.new(-1,2) end it "Se debe calcular el valor absoluto de una fraccion con el metodo abs" do @rac.new(-2,3).abs.should == @rac.new(2,3) @rac.new(2,-4).abs.should == @rac.new(1,2) end it "Se debe calcular el reciproco de una fraccion con el metodo reciprocal" do @rac.new(-2,3).reciproco.should == @rac.new(-3,2) @rac.new(21,3).reciproco.should == @rac.new(1,7) end it "Se debe calcular el opuesto de una fraccion con - " do (-@rac.new(2,4)).should == @rac.new(-1,2) (-@rac.new(-1,3)).should == @rac.new(1,3) end it "Se debe sumar dos fracciones con + y dar el resultado de forma reducida" do (@rac.new(1,2) + @rac.new(1,4)).should == @rac.new(3,4) (@rac.new(5,15) + @rac.new(2,3)).should == @rac.new(1,1) end it "Se debe restar dos fracciones con - y dar el resultado de forma reducida" do (@rac.new(6,8) - @rac.new(1,4)).should == @rac.new(1,2) (@rac.new(3,3) - @rac.new(2,6)).should == @rac.new(2,3) end it "Se debe multiplicar dos fracciones con * y dar el resultado de forma reducida" do (@rac.new(1,2) * @rac.new(2,4)).should == @rac.new(1,4) (@rac.new(-3,3) * @rac.new(2,6)).should == @rac.new(-1,3) end it "Se debe dividir dos fracciones con / y dar el resultado de forma reducida" do (@rac.new(2,3) / @rac.new(2,4)).should == @rac.new(4,3) (@rac.new(-6,16) / @rac.new(2,6)).should == @rac.new(-9,8) end it "Se debe calcular el resto dos fracciones con % y dar el resultado de forma reducida" do (@rac.new(5,1) % @rac.new(2,1)).should == 1 (@rac.new(17,1) % @rac.new(3,1)).should == 2 end it "Se debe de poder comprobar si una fracion es menor que otra" do (@rac.new(1, 2) < @rac.new(3, 4)).should be_true (@rac.new(1, 2) < @rac.new(1, 4)).should be_false end it "Se debe de poder comprobar si una fracion es mayor que otra" do (@rac.new(1, 2) > @rac.new(3, 4)).should be_false (@rac.new(1, 2) > @rac.new(1, 4)).should be_true end it "Se debe de poder comprobar si una fracion es menor o igual que otra" do (@rac.new(1, 2) <= @rac.new(2, 4)).should be_true (@rac.new(1, 2) <= @rac.new(3, 4)).should be_true end it "Se debe de poder comprobar si una fracion es mayor o igual que otra" do (@rac.new(1, 2) >= @rac.new(2, 4)).should be_true (@rac.new(3, 2) >= @rac.new(3, 4)).should be_true end end
class Venue < ActiveRecord::Base has_many :gigs geocoded_by :address after_validation :geocode end
namespace :brewery_db do namespace :synchronize do things = %w[ingredients events guilds breweries styles beers locations].map(&:to_sym) things.each do |thing| desc "Synchronizes #{thing} with BreweryDB's data. Adds, updates, and removes as necessary." task thing => :environment do puts "Synchronizing #{thing}..." klass = "brewery_d_b/synchronizers/#{thing}".classify.constantize synchronizer = klass.new synchronizer.synchronize! synchronizer.handle_removed! unless thing.in?([:ingredients, :styles]) end end desc 'Synchronizes all data with BreweryDB. Adds, updates, and removes as necessary.' task :all => things end end
class AddQuestionCountToTopics < ActiveRecord::Migration[5.0] def change add_column :topics, :questions_count, :integer, default: 0 add_column :topics, :recursive_questions_count, :integer, default: 0 end end
require 'rails_helper' RSpec.describe Goal, type: :model do describe 'validations' do it {should validate_presence_of(:user_id)} it {should validate_presence_of(:completed)} it {should validate_presence_of(:private)} it {should validate_presence_of(:details)} it {should validate_presence_of(:title)} end describe "associations" do it {should belong_to(:user)} end end
class Ability include CanCan::Ability def initialize(user) if user && user.admin? can :access, :rails_admin # only allow admin users to access Rails Admin can :dashboard # allow access to dashboard end if user && user.admin? can :manage, [Group, Server, User] can :show, :group_settings else can :read, Group, :user_groups => {:user_id => user.id, :read => true} can :update, Group, :user_groups => {:user_id => user.id, :manage => true} can :read, Server, :group => { :user_groups => { :user_id => user.id, :read => true } } can :update, Server, :group => { :user_groups => { :user_id => user.id, :edit => true } } can :manage, Server, :group => { :user_groups => { :user_id => user.id, :manage => true } } can :show, :group_settings do user.user_groups.any? do |user_group| user_group.manage end end end end end
class CreateNats < ActiveRecord::Migration[5.1] def change create_table :nats do |t| t.string :name t.integer :ext_port t.integer :int_port t.string :int_ip t.boolean :state t.string :owner t.timestamps end add_index :nats, :ext_port, unique: true end end
def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end WIN_COMBINATIONS = [[0, 1, 2],[3, 4, 5],[6, 7, 8],[2, 5, 8],[1, 4, 7],[0, 3, 6],[0, 4, 8],[6, 4, 2]] def won?(board) WIN_COMBINATIONS.detect do |combo| board[combo[0]] == "X" && board[combo[1]] == "X" && board[combo[2]] == "X" || board[combo[0]] == "O" && board[combo[1]] == "O" && board[combo[2]] == "O" end end def full?(board) board.none? (" ") end def draw?(board) !won?(board) end def over?(board) won?(board) || full?(board) end def winner(board) x = won?(board).to_a[0] if over?(board) == false return nil elsif board[x] == "X" return "X" elsif board[x] == "O" return "O" end end #[board[x]].detect{|i| i == "X"} #while over?(board) == true #x = won?(board) #array = x.to_a #array[0].include? ("X" || "O") #end #end #array = won?(board).to_a #x = array.to_a #y = x[0] #if board[y] == "X" #puts "X" #if board[y] == "O" #puts "O" #end #end #end
class Ship attr_reader :location, :type, :xsize def initialize(matrix, options) @xsize = options[:size] @type = options[:type] @matrix = matrix @location = [] end def build begin destroy ship_len = @xsize mask = [] # random start point begin xy = [rand(@matrix.size), rand(@matrix.size)] mask = take_mask(xy) end while mask.empty? save(xy) ship_len -= 1 while(!ship_len.zero? && !mask.size.zero?) do # random next direction xy = mask.delete_at(rand(mask.size)) neighberhood = take_mask(xy, @location.last) if !neighberhood.empty? save(xy) mask = neighberhood ship_len -= 1 end end end while !ship_len.zero? self end private def destroy @location.each { |xy| @matrix[xy[0]][xy[1]] = ' ' } @location = [] end def save(xy) @location.push(xy) @matrix[xy[0]][xy[1]] = true end # returns valid surrounding mask def take_mask(xy, exception = nil) return [] unless xy x, y = xy[0], xy[1] return [] if @matrix[x][y] === true mask = Array.new mask[0] = [x-1, y ] if (x-1) >= 0 mask[1] = [x, y-1] if (y-1) >= 0 mask[2] = [x, y+1] if (y+1) < @matrix.size mask[3] = [x+1, y ] if (x+1) < @matrix.size clean(mask, exception) end def clean(mask, exception) mask = mask.select{ |item| not item.nil? || item === exception } mask.each do |item| if @matrix[item[0]][item[1]] === true return [] end end mask end end
class Link include Mongoid::Document include AASM include Mongoid::Timestamps field :href, type: String field :description, type: String field :aasm_state validates :href, presence: true validates :description, length: { maximum: 200 } before_save :normalize_href, if: :invalid_format? belongs_to :user has_and_belongs_to_many :tags # User could share link to all user aasm do state :private, initial: true state :public event :share do transitions from: :private, to: :public end event :hide do transitions from: :public, to: :private end end def tag_list tags.map(&:name).join(', ') end def tag_list=(names) self.tags = names.split(',').map do |n| Tag.where(name: n.strip).first_or_create! end end def self.tagged_with(id) Link.where(tag_ids: id) end private def invalid_format? return true unless href =~ /^http/ false end def normalize_href href.prepend('http://') end end
class FixSendtForMailings < ActiveRecord::Migration def up rename_column :mailings, :sendt_at, :send_at change_column :mailings, :send_at, :time end def down change_column :mailings, :send_at, :date rename_column :mailings, :send_at, :sendt_at end end
require 'spec_helper' describe EssayStyle do subject { described_class.new } [:title].each do |field| it "has the ##{field} attribute" do expect(subject).to respond_to(field) expect(subject).to respond_to("#{field}=") end end describe '#friendly_id' do it "is based on the title" do subject.title = 'Test' subject.save expect(subject.friendly_id).to be == 'test' end end describe '#essays' do subject { FactoryBot.create(:essay_style) } it 'has many essays' do expect{ FactoryBot.create_list(:essay, 2, essay_style_id: subject.id) }.to change{ subject.essays.count }.by(2) end end end
class Actor <ApplicationRecord validates_presence_of :name has_many :movie_actors has_many :movies, through: :movie_actors def associates movies.joins(:actors).where('name !=?', self.name).order("name").distinct.pluck(:name).join(", ") # I had trouble with the `order` method. # Is there a way to order by the join table name without using a sql injection? # it would have been nice to have .order(actor.name)... or something like that end end
class AddStateToOrders < ActiveRecord::Migration[5.1] def change add_column :orders, :payment_status, :integer, default: "0", null: false rename_column :orders, :status, :order_status end end
require 'spec_helper' describe Post do it { should respond_to :title } it { should respond_to :content } it { should respond_to :comments_count } it { should respond_to :user_id } it { should respond_to :created_at } end
class QuickReplacementOrder < ReplacementOrder state_machine :initial => :claim_asset_product do command :record_replacement_product, :parent_name => :order do transition :claim_asset_product => :complete end after_transition :on => :record_replacement_product do |replacement_order| replacement_order.claim.record_replacement_order end end end
# == Schema Information # # Table name: issues # # id :integer not null, primary key # project_id :integer # user_id :integer # assignee_id :integer # subject :string(255) # description :text # status :integer # created_at :datetime not null # updated_at :datetime not null # priority :integer # require 'spec_helper' describe Issue do before { @issue = FactoryGirl.create(:issue) } subject { @issue } it { should respond_to :project } it { should respond_to :user } it { should respond_to :assignee } it { should respond_to :subject } it { should respond_to :description } it { should respond_to :status } it { should respond_to :priority } it { should be_valid } its(:status) { should == Status::ACTIVE } its(:priority) { should == Priority::NORMAL } describe 'without subject' do before { @issue.subject = nil } it { should_not be_valid } end describe 'with too short subject' do before { @issue.subject = 'a' * 7 } it { should_not be_valid } end describe 'with too long subject' do before { @issue.subject = 'a' * 101 } it { should_not be_valid } end describe 'without a project' do before { @issue.project_id = nil } it { should_not be_valid } end describe 'without an opener' do before { @issue.user_id = nil } it { should_not be_valid } end end
require 'ElevatorMedia' require 'spec_helper' describe ElevatorMedia do describe "Weather" do streamer = ElevatorMedia::Streamer.new("07112") context "test to get Streamer class" do it "return Streamer class" do expect(streamer).to be_a(ElevatorMedia::Streamer) end end context "test to get http request" do it "return JSON" do expect(streamer.call).to be_a(Hash) end end context "test to get building details" do it "return string" do content = streamer.getContent puts content expect(content).to include("<div>", "</div>") end end end end
class Types::FormTypeType < Types::BaseEnum Form::FORM_TYPE_CONFIG.each do |key, config| value key, config['description'].capitalize end end
Rails.application.routes.draw do get '/cities' => 'cities#index' end
require 'semverly' require 'open3' require 'bundler' require_relative '../base/engine' module CapsuleCD module Node class NodeEngine < Engine def build_step super # validate that the chef metadata.rb file exists unless File.exist?(@source_git_local_path + '/package.json') fail CapsuleCD::Error::BuildPackageInvalid, 'package.json file is required to process Npm package' end # no need to bump up the version here. It will automatically be bumped up via the npm version patch command. # however we need to read the version from the package.json file and check if a npm module already exists. # TODO: check if this module name and version already exist. # check for/create any required missing folders/files unless File.exist?(@source_git_local_path + '/test') FileUtils.mkdir(@source_git_local_path + '/test') end unless File.exist?(@source_git_local_path + '/.gitignore') CapsuleCD::GitUtils.create_gitignore(@source_git_local_path, ['Node']) end end def test_step super # the module has already been downloaded. lets make sure all its dependencies are available. Open3.popen3('npm install', chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestDependenciesError, 'npm install failed. Check module dependencies' end end # create a shrinkwrap file. Open3.popen3('npm shrinkwrap', chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestDependenciesError, 'npm shrinkwrap failed. Check log for exact error' end end # run test command test_cmd = @config.engine_cmd_test || 'npm test' Open3.popen3(ENV, test_cmd, chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestRunnerError, test_cmd + ' failed. Check log for exact error' end end unless @config.engine_disable_test end # run npm publish def package_step super # commit changes to the cookbook. (test run occurs before this, and it should clean up any instrumentation files, created, # as they will be included in the commmit and any release artifacts) CapsuleCD::GitUtils.commit(@source_git_local_path, 'Committing automated changes before packaging.') rescue puts 'No changes to commit..' # run npm publish Open3.popen3("npm version #{@config.engine_version_bump_type} -m '(v%s) Automated packaging of release by CapsuleCD'", chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join fail 'npm version bump failed' unless external.value.success? end @source_release_commit = CapsuleCD::GitUtils.get_latest_tag_commit(@source_git_local_path) end # this step should push the release to the package repository (ie. npm, chef supermarket, rubygems) def release_step super npmrc_path = File.expand_path('~/.npmrc') unless @config.npm_auth_token fail CapsuleCD::Error::ReleaseCredentialsMissing, 'cannot deploy page to npm, credentials missing' end # write the knife.rb config file. File.open(npmrc_path, 'w+') do |file| file.write("//registry.npmjs.org/:_authToken=#{@config.npm_auth_token}") end # run npm publish Open3.popen3('npm publish .', chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::ReleasePackageError, 'npm publish failed. Check log for exact error' end end end end end end
require './lib/card.rb' class Deck attr_accessor :cards def initialize create_deck shuffle_deck end def create_deck @cards = [] suits = [:spades, :clubs, :hearts, :diamonds] for i in 2..14 do suits.each do |suit| @cards << Card.new(suit, i) end end end def shuffle_deck @cards.shuffle! end def deal_card @cards.pop end def count @cards.count end end
class AddDefaultVoteCountToOptions < ActiveRecord::Migration[6.1] def change change_column :options, :vote_count, :integer, default: 0 end end
# frozen_string_literal: true # The Metric class represents a metric sample to be send by a backend. # # @!attribute type # @return [Symbol] The metric type. Must be one of {StatsD::Instrument::Metric::TYPES} # @!attribute name # @return [String] The name of the metric. {StatsD#prefix} will automatically be applied # to the metric in the constructor, unless the <tt>:no_prefix</tt> option is set or is # overridden by the <tt>:prefix</tt> option. Note that <tt>:no_prefix</tt> has greater # precedence than <tt>:prefix</tt>. # @!attribute value # @see #default_value # @return [Numeric, String] The value to collect for the metric. Depending on the metric # type, <tt>value</tt> can be a string, integer, or float. # @!attribute sample_rate # The sample rate to use for the metric. How the sample rate is handled differs per backend. # The UDP backend will actually sample metric submissions based on the sample rate, while # the logger backend will just include the sample rate in its output for debugging purposes. # @see StatsD#default_sample_rate # @return [Float] The sample rate to use for this metric. This should be a value between # 0 and 1. If not set, it will use the default sample rate set to {StatsD#default_sample_rate}. # @!attribute tags # The tags to associate with the metric. # @note Only the Datadog implementation supports tags. # @see .normalize_tags # @return [Array<String>, Hash<String, String>, nil] the tags to associate with the metric. # You can either specify the tags as an array of strings, or a Hash of key/value pairs. # # @see StatsD The StatsD module contains methods that generate metric instances. # @see StatsD::Instrument::Backend A StatsD::Instrument::Backend is used to collect metrics. # class StatsD::Instrument::Metric unless Regexp.method_defined?(:match?) # for ruby 2.3 module RubyBackports refine Regexp do def match?(str) (self =~ str) != nil end end end using RubyBackports end def self.new(type:, name:, value: default_value(type), tags: nil, metadata: nil, sample_rate: StatsD.legacy_singleton_client.default_sample_rate) # pass keyword arguments as positional arguments for performance reasons, # since MRI's C implementation of new turns keyword arguments into a hash super(type, name, value, sample_rate, tags, metadata) end # The default value for this metric, which will be used if it is not set. # # A default value is only defined for counter metrics (<tt>1</tt>). For all other # metric types, this emthod will raise an <tt>ArgumentError</tt>. # # # A default value is only defined for counter metrics (<tt>1</tt>). For all other # metric types, this emthod will raise an <tt>ArgumentError</tt>. # # @return [Numeric, String] The default value for this metric. # @raise ArgumentError if the metric type doesn't have a default value def self.default_value(type) case type when :c then 1 else raise ArgumentError, "A value is required for metric type #{type.inspect}." end end attr_accessor :type, :name, :value, :sample_rate, :tags, :metadata # Initializes a new metric instance. # Normally, you don't want to call this method directly, but use one of the metric collection # methods on the {StatsD} module. # # @param type [Symbol] The type of the metric. # @option name [String] :name The name of the metric without prefix. # @option value [Numeric, String, nil] The value to collect for the metric. # @option sample_rate [Numeric, nil] The sample rate to use. If not set, it will use # {StatsD#default_sample_rate}. # @option tags [Array<String>, Hash<String, String>, nil] :tags The tags to apply to this metric. # See {.normalize_tags} for more information. def initialize(type, name, value, sample_rate, tags, metadata) # rubocop:disable Metrics/ParameterLists raise ArgumentError, "Metric :type is required." unless type raise ArgumentError, "Metric :name is required." unless name raise ArgumentError, "Metric :value is required." unless value @type = type @name = normalize_name(name) @value = value @sample_rate = sample_rate @tags = StatsD::Instrument::Metric.normalize_tags(tags) if StatsD.legacy_singleton_client.default_tags @tags = Array(@tags) + StatsD.legacy_singleton_client.default_tags end @metadata = metadata end # @private # @return [String] def to_s str = +"#{name}:#{value}|#{type}" str << "|@#{sample_rate}" if sample_rate && sample_rate != 1.0 str << "|#" << tags.join(',') if tags && !tags.empty? str end # @private # @return [String] def inspect "#<StatsD::Instrument::Metric #{self}>" end # The metric types that are supported by this library. Note that every StatsD server # implementation only supports a subset of them. TYPES = { c: 'increment', ms: 'measure', g: 'gauge', h: 'histogram', d: 'distribution', kv: 'key/value', s: 'set', } # Strip metric names of special characters used by StatsD line protocol, replace with underscore # # @param name [String] # @return [String] def normalize_name(name) # fast path when no normalization is needed to avoid copying the string return name unless /[:|@]/.match?(name) name.tr(':|@', '_') end # Utility function to convert tags to the canonical form. # # - Tags specified as key value pairs will be converted into an array # - Tags are normalized to only use word characters and underscores. # # @param tags [Array<String>, Hash<String, String>, nil] Tags specified in any form. # @return [Array<String>, nil] the list of tags in canonical form. def self.normalize_tags(tags) return unless tags tags = tags.map { |k, v| k.to_s + ":" + v.to_s } if tags.is_a?(Hash) # fast path when no string replacement is needed return tags unless tags.any? { |tag| /[|,]/.match?(tag) } tags.map { |tag| tag.tr('|,', '') } end end
module GluttonRatelimit def rate_limit symbol, executions, time_period, rl_class = AveragedThrottle rl = rl_class.new executions, time_period old_symbol = "#{symbol}_old".to_sym alias_method old_symbol, symbol define_method symbol do |*args| rl.wait self.send old_symbol, *args end end private # All the other classes extend this parent and are therefore # constructed in the same manner. class ParentLimiter attr_reader :executions def initialize executions, time_period @executions = executions @time_period = time_period end def times(num, &block) raise ArgumentError, "Code block expected" if not block raise ArgumentError, "Parameter expected to be #{Integer.to_s} but found a #{num.class}." unless num.kind_of?(Integer) num.times do wait yield end end end end dir = File.expand_path(File.dirname(__FILE__)) require File.join(dir, "glutton_ratelimit", "bursty_ring_buffer") require File.join(dir, "glutton_ratelimit", "bursty_token_bucket") require File.join(dir, "glutton_ratelimit", "averaged_throttle")
class Auth::Slack < Grape::API namespace :auth do params do requires :code, desc: 'Oauth code from slack' end post :slack do authenticator = SlackAuth.new(params[:code]) user = User.from_slack(authenticator.user_info) user.save { auth_token: user.auth_token } end end end
class YankProposalsController < ApplicationController def index @yank_proposals = YankProposal.all end def new @yank_proposal = YankProposal.new end def create @yank_proposal = YankProposal.new(params[:yank_proposal]) if @yank_proposal.save flash[:success] = "We've added your stock to the database. It will be processed shortly." else flash[:error] = "We couldn't add your stock to the database." end redirect_to new_yank_proposal_path end def approve @yank_proposal = YankProposal.find(params[:id]) @stock_yank = StockYank.new(:name => @yank_proposal.name, :symbol => @yank_proposal.symbol) if @stock_yank.save flash[:success] = "Proposal added to stock yanks" else flash[:error] = "Couldn't add proposal" end @yank_proposal.destroy update_quotes redirect_to yank_proposals_path end def destroy @yank_proposal = YankProposal.find(params[:id]) if @yank_proposal.destroy flash[:success] = "Proposal destroyed" else flash[:error] = "Proposal wasn't destroyed" end redirect_to yank_proposals_path end end
require 'rails_helper' RSpec.describe Link, type: :model do describe 'associations' do it { should belong_to(:linkable) } end describe 'validations' do it { should validate_presence_of :name } context 'url' do it { should validate_presence_of :url } it { should_not allow_value('http:/foo.com/bar').for(:url) } it { should_not allow_value('ftp:/foo.com').for(:url) } it { should_not allow_value('http//foo.com').for(:url) } it { should allow_value('http://foo.com/blah_blah').for(:url) } it { should allow_value('https://foo.com/blah_blah').for(:url) } end end describe 'scopes' do let!(:question) { create(:question) } let!(:link1) { create(:link, linkable: question) } let!(:link2) { create(:link, linkable: question) } context 'default scope by created_at: :asc' do subject { question.links.to_a } it { is_expected.to match_array [link1, link2] } end end describe 'callbacks' do it { should callback(:save_gist_body!).after(:create).if(:gist?) } let(:gist) do Link.create( name: 'Gist', url: 'https://gist.github.com/FoRuby/f7059ba947b5d0138f302f8e43694348', linkable: create(:question) ) end let(:link) { create(:link) } context 'if link url = gist url => link.gist_body', :vcr do subject { gist.gist_body } it { is_expected.to eq('GistTitle') } end context 'if link url != gist url => link.gist_body' do subject { link.gist_body } it { is_expected.to be_nil } end end describe 'methods' do context '#gist?' do let(:gist) do create(:gist, name: 'Gist', url: 'https://gist.github.com/test/test', gist_body: 'GistBody') end let(:link) { create(:link) } context 'gist', :vcr do subject { gist } it { is_expected.to be_gist } end context 'link' do subject { link } it { is_expected.not_to be_gist } end end end end
class RacesController < ApplicationController def index @races = current_user.races end def show @race = Race.find_by(id: params[:id]) end def new @race = Race.new end def create @race = current_user.races.build(race_params) if @race.save redirect_to race_path(@race) else render :new end end def edit @race = Race.find_by(id: params[:id]) end def update @race = Race.find_by(id: params[:id]) if @race.update(race_params) redirect_to race_path(@race) else render :edit end end private def race_params params.require(:race).permit(:title, :distance, :category) end # require the model # permit the attributes you want to allow in # strong params end
class Customer < Base def self.columns [:id, :first_name, :last_name, :created_at, :updated_at] end def invoices InvoiceRepository.find_all_by_customer_id(self.id) end end
#designing methods for controllers # first thing specifying routes # @@ Configu # go to routes # inside routes.draw do () end ## get "/bleats" # this will in the example get the bleats #gets is a method that gets called on self # after this, the router needs to specify which controller actions it needs to go to ## get "/bleats", to: "bleats#index" # calling index action on bleats controller # @ app >controller create a file called # bleats_controller.rb # class BleatsControllers < ActionController::Base #render plain: "hello world" # end ## how to start server : #bundle exec rails server ### useful gems # gem 'better_errors' # gem 'binding_of_colors' ##communicating through json # bleats_controller.rb # class BleatsControllers < ActionController::Base # render json: '{"tommy": "hello"}' #JSON, javasrcript object notation, key: value pair # end ### sending back infos # bleats_controller.rb # class BleatsControllers < ActionController::Base # bleats = Bleats.all # render json: bleats # ## building show action ##@@@ inside routes ## Rails.application.route.draw do # get"/bleats", to: "bleats#index" # get"/bleats/:id" to: "bleats#show" ## the :id is the wildcard or varaible given to the request ##end ## @@ BleatsControler # bleats_controller.rb # class BleatsControllers < ActionController::Base # def post # bleats = Bleats.all # render json: bleats # end # def show #bleat = Bleat.find(params[:id]) # parameter is a method that finds the thing passed in # because show is a method getting called on .self #which is a long data, param[id] is necessary to specify :id #render json: bleat #end ## @@ BleatsController # create action ##@@@ inside routes ## Rails.application.route.draw do # get"/bleats", to: "bleats#index" # get"/bleats/:id" to: "bleats#show" ## the :id is the wildcard or varaible given to the request # post"/bleats", to: "bleast#create" ##end ##@@ insides bleats controller # bleats_controller.rb # class BleatsControllers < ActionController::Base # def index # bleats = Bleats.all # render json: bleats # end # def show #bleat = Bleat.find(params[:id]) # parameter is a method that finds the thing passed in # because show is a method getting called on .self #which is a long data, param[id] is necessary to specify :id #render json: bleat #end ## def create # bleats_param = Bleat.new(params.require(:bleat),permit(:author_id, :body) #bleat = Bleat.new(bleat_params) # # if bleat.save # .save returns true or false if it saved or not # render json: bleat #else # render json: bleat.errors.full_messages, status: 422 #422 is unrprocessable entity #end #end #end #how to bypass identity authentication token ##@@@ inside app controler #class Ap #skip_before_action: verify_authenticity_token #end ### save vs save! # save renders the error and moves on while save! terminates the process without moving on to the later part ### update & destory actions, and resourceful routes ## how to change something that is already in the database = put or patch #patch request patches onluy some elemtnes of existing database #put can overwrite all existing data ## syntax : ##@@@ inside routes ## Rails.application.route.draw do # get"/bleats", to: "bleats#index" # get"/bleats/:id" to: "bleats#show" ## the :id is the wildcard or varaible given to the request # post"/bleats", to: "bleast#create" # put "/bleats/:id", to: "bleats#update" ##end ##@@ insides bleats controller # bleats_controller.rb # class BleatsControllers < ActionController::Base # def index # bleats = Bleats.all # render json: bleats # end # def show #bleat = Bleat.find(params[:id]) # parameter is a method that finds the thing passed in # because show is a method getting called on .self #which is a long data, param[id] is necessary to specify :id #render json: bleat #end ## def create # bleats_param = Bleat.new(params.require(:bleat),permit(:author_id, :body) #bleat = Bleat.new(bleat_params) # # if bleat.save # .save returns true or false if it saved or not # render json: bleat #else # render json: bleat.errors.full_messages, status: 422 #422 is unrprocessable entity #end # def update <<- #bleat = Bleat.find(params[:id]) # bleats_param = Bleat.new(params.require(:bleat),permit(:author_id, :body) #if bleat.update(bleat_params) # update returns true or false # render json: bleat # else # render json: bleat.errors.full_messages, status: 422 #end #end #private # def bleat_params << this makes this easily accessible on other methods # # bleats_param = Bleat.new(params.require(:bleat),permit(:author_id, :body) # end #end #### Delete request ## syntax : ##@@@ inside routes ## Rails.application.route.draw do # get"/bleats", to: "bleats#index" # get"/bleats/:id" to: "bleats#show" ## the :id is the wildcard or varaible given to the request # post"/bleats", to: "bleast#create" # put "/bleats/:id", to: "bleats#update" # delete "/bleats/:id", to: "bleat#destroy" <<<- ##end ##@@ insides bleats controller # bleats_controller.rb # class BleatsControllers < ActionController::Base # def index # bleats = Bleats.all # render json: bleats # end # def show #bleat = Bleat.find(params[:id]) # parameter is a method that finds the thing passed in # because show is a method getting called on .self #which is a long data, param[id] is necessary to specify :id #render json: bleat #end ## def create # bleats_param = Bleat.new(params.require(:bleat),permit(:author_id, :body) #bleat = Bleat.new(bleat_params) # # if bleat.save # .save returns true or false if it saved or not # render json: bleat #else # render json: bleat.errors.full_messages, status: 422 #422 is unrprocessable entity #end # def update #bleat = Bleat.find(params[:id]) # bleats_param = Bleat.new(params.require(:bleat),permit(:author_id, :body) #if bleat.update(bleat_params) # update returns true or false # render json: bleat # else # render json: bleat.errors.full_messages, status: 422 #end #end #def destory <<< -- # bleat = Bleat.find(params[:id]) # bleat.destroy # render json: "successfully destoryed" # end # find returns an error if there nothing, never returns a nil #private # def bleat_params << this makes this easily accessible on other methods # # bleats_param = Bleat.new(params.require(:bleat),permit(:author_id, :body) # end #end # delete vs destroy # delete calls sql actions, but it can still leave traces # destory destorys all of it's associated things(all other dependencies)
json.array!(@hoteis) do |hotel| json.extract! hotel, :id, :nome, :cnpj, :email json.url hotel_url(hotel, format: :json) end
require 'rails_helper' describe 'an admin' do context 'visiting conditions index' do it 'can delete a condition and view an accompanying flash message' do admin = create(:user, role: 1) condition_1 = create(:condition, max_temperature_f: 500) condition_2 = create(:condition, max_temperature_f: 400) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit conditions_path within "#condition-#{condition_1.id}" do click_on 'Delete' end expect(current_path).to eq(conditions_path) expect(page).to_not have_content(condition_1.max_temperature_f) expect(page).to have_content("Condition for #{condition_1.date} was deleted!") end end end
class MessageThreadSubscription < ActiveRecord::Base belongs_to :user belongs_to :thread delegate :messages, to: :thread end
require "spec_helper" describe Lob::V1::BankAccount do before :each do @sample_address_params = { name: "TestAddress", email: "test@test.com", address_line1: "123 Test Street", address_line2: "Unit 199", address_city: "Mountain View", address_state: "CA", address_country: "US", address_zip: 94085 } @sample_bank_account_params = { routing_number: "122100024", account_number: "123456789" } end subject { Lob(api_key: ENV["LOB_API_KEY"]) } describe "list" do it "should list bank accounts" do assert subject.bank_accounts.list["object"] == "list" end end describe "create" do it "should create a bank account with address_id" do new_address = subject.addresses.create @sample_address_params result = subject.bank_accounts.create( routing_number: @sample_bank_account_params[:routing_number], bank_address: new_address["id"], account_number: @sample_bank_account_params[:account_number], account_address: new_address["id"], signatory: "John Doe" ) result["account_number"].must_equal(@sample_bank_account_params[:account_number]) end it "should create a bank account with address params" do result = subject.bank_accounts.create( routing_number: @sample_bank_account_params[:routing_number], bank_address: @sample_address_params.clone, account_number: @sample_bank_account_params[:account_number], account_address: @sample_address_params.clone, signatory: "John Doe" ) result["account_number"].must_equal(@sample_bank_account_params[:account_number]) end end describe "find" do it "should find a bank account" do new_address = subject.addresses.create @sample_address_params new_bank_account = subject.bank_accounts.create( routing_number: @sample_bank_account_params[:routing_number], bank_address: new_address["id"], account_number: @sample_bank_account_params[:account_number], account_address: new_address["id"], signatory: "John Doe" ) result = subject.bank_accounts.find(new_bank_account["id"]) result["id"].must_equal(new_bank_account["id"]) end end describe "destroy" do it "should delete a bank_account" do new_bank_account = subject.bank_accounts.create( routing_number: @sample_bank_account_params[:routing_number], bank_address: @sample_address_params.clone, account_number: @sample_bank_account_params[:account_number], account_address: @sample_address_params.clone, signatory: "John Doe" ) delete_result = subject.bank_accounts.destroy(new_bank_account["id"]) assert_equal(new_bank_account["id"], delete_result["id"]) end end describe "verify" do it "should verify a bank account" do new_bank_account = subject.bank_accounts.create( routing_number: @sample_bank_account_params[:routing_number], bank_address: @sample_address_params.clone, account_number: @sample_bank_account_params[:account_number], account_address: @sample_address_params.clone, signatory: "John Doe" ) verify_result = subject.bank_accounts.verify(new_bank_account["id"], amounts: [12, 34]) assert_equal(new_bank_account["id"], verify_result["id"]) end end end
class Bullshit def self.is_bullshit? word @bullshits = YAML.load_file("#{RAILS_ROOT}/db/bullshits.yml").split.map(&:downcase) @bullshits.include? word.match(/(\w+)/i)[0].downcase end end
class Message < ApplicationRecord after_create_commit { MessageBroadcastJob.perform_later self } belongs_to :sent_user, class_name: "User", foreign_key: 'user_id' belongs_to :room validates :content, presence: true end
class ReviewsController < ApplicationController def index @reviews = Review.asc(:created_at).page params[:page] @comment = Comment.new end def show @review = Review.find(params[:id]) @comment = ReviewComment.new end def photo content = @review.photo.read if stale?(etag: content, last_modified: @review.updated_at.utc, public: true) send_data content, type: @review.photo.file.content_type, disposition: "inline" expires_in 0, public: true end end end
class AddColumnToWishItem < ActiveRecord::Migration[5.0] def change add_column :wish_items, :wishlist_id, :integer end end
require 'sinatra' require 'sinatra/support' require_relative 'helpers' require_relative 'core/runner' configure do set :public_folder, Proc.new { File.join( root, "static" ) } enable :sessions end ### # The online version will handle multiple running instances # The offline version won't, so we define this globally for now $runner = RubiesInSpaceRunner.new before do @snapshot = $runner.instance.snapshot session[ :state ] = @snapshot.state end #=====-=====-=====-=====-=====-=====# # Home #=====-=====-=====-=====-=====-=====# get '/' do erb :index end #=====-=====-=====-=====-=====-=====# # Simulation #=====-=====-=====-=====-=====-=====# get '/simulation' do erb :'simulation/index' end post '/simulation' do try_setting_simulation( params ) redirect to '/simulation' end #=====-=====-=====-=====-=====-=====# # Exploration #=====-=====-=====-=====-=====-=====# get '/explore' do if $runner.universe.nil? redirect to '/simulation' else @page = 0 erb :'explore/index' end end get '/explore/page/:n' do if $runner.universe.nil? redirect to '/simulation' else @page = params[ :n ].to_i erb :'explore/index' end end get '/explore/:id' do if $runner.universe.nil? redirect to '/simulation' else @node = $runner.universe.nodes[ params[ :id ].to_i ] if @node.nil? redirect to '/explore' else erb :'explore/show' end end end #=====-=====-=====-=====-=====-=====# # Logger #=====-=====-=====-=====-=====-=====# get '/log' do if $runner.universe.nil? redirect to '/simulation' else @page = 0 erb :'simulation/log' end end get '/log/page/:n' do if $runner.universe.nil? redirect to '/simulation' else @page = params[ :n ].to_i erb :'simulation/log' end end get '/log/:date' do if $runner.universe.nil? redirect to '/simulation' else @stardate = Space::Universe.stardate params[ :date ].to_i @logs = Space::Universe.logger[ params[ :date ].to_i ] #@next = if @logs.nil? redirect to '/log' else erb :'simulation/log_entry' end end end #=====-=====-=====-=====-=====-=====# # Ships #=====-=====-=====-=====-=====-=====# get '/ships' do if $runner.universe.nil? redirect to '/simulation' else erb :'ships/index' end end get '/ship/:id' do ships = ( $runner.players.map do | player | player.ships end ).flatten @ship = ships.find do | ship | ship.id.to_s == params[ :id ] end puts "", "", "s:" + @ship.to_s if @ship.nil? redirect to '/ships' else erb :'ships/show' end end #=====-=====-=====-=====-=====-=====# # Players #=====-=====-=====-=====-=====-=====# get '/player/:id' do @player = $runner.players.find do |p| p.id.to_s == params[ :id ] end if @player.nil? redirect to '/players' else erb :'players/show' end end get '/players/join' do erb :'players/join' end get '/players' do erb :'players/index' end post '/players' do unless try_adding_player( params ) redirect to session[ :previous_url ] || '/players/join' else redirect to '/players' end end get '/crews' do erb :'players/crews' end
class DeviceInformation < ActiveRecord::Base belongs_to :feedback attr_accessible :feedback, :os_name, :os_version, :model validates :os_name, :presence => true validates :os_version, :presence => true end
class Signed::AdminsController < ApplicationController layout 'signed' before_filter :authenticate_signed_user! end
class BudgetsController < ApplicationController before_action :logged_in_user def index @budgets = Budget.all @employers = Employer.all end def show @budget = Budget.find(params[:id]) @employer = @budget.employer @timesheets = @budget.timesheets @employees = @budget.employees.distinct.order(:id) end def new @budget = Budget.new @employer = Employer.new end def create @budget = Budget.new(budget_params) if @budget.save flash[:success] = "Budget created" redirect_to budgets_path else flash[:danger] = "Budget was not created" render 'new' end end def edit @budget = Budget.find(params[:id]) @employer = @budget.employer end def update @budget = Budget.find(params[:id]) @employer = @budget.employer if @budget.update(budget_update_params) flash[:success] = "Budget updated" redirect_to budgets_path else flash.now[:danger] = "Budget was not updated" render 'edit' # respond_with(@budget) end end def destroy @budget = Budget.find(params[:id]).destroy flash.now[:success] = "Budget and any associated timesheets were deleted" redirect_to budgets_path end private def budget_params params.require(:budget).permit(:employer_id, :hours, :start_date, :end_date) end def budget_update_params params.require(:budget).permit(:hours, :start_date, :end_date) end end
class DropDecksTableAndHandsTable < ActiveRecord::Migration[5.2] def change drop_table :decks drop_table :hands end end
class Book < ActiveRecord::Base belongs_to :author belongs_to :category belongs_to :publisher validates :title, presence: true, length: { minimum: 2, maximum: 255 } validates :category_id, presence: true validates :author_id, presence: true validates :publisher_id, presence: true validates :isbn, presence: true validates :year, presence: true, numericality: true validates :price, presence: true, numericality: true validates :buy, presence: true, length: {minimum: 7} validates :format, presence: true, length: { minimum: 3, maximum: 255 } validates :pages, presence: true, numericality: true end
#! /usr/bin/env ruby # TODO: # - currently only works for ssh # - won't work for forks (or will it?) # - doesn't deal with multiple PRs for a branch require 'io/console' require 'git' require 'github_api' git_dir = Dir.new(Dir.pwd) until git_dir.entries.include? '.git' parent_path = git_dir.path[/.*(?=\/.*$)/] git_dir = Dir.new(parent_path) end git = Git.open(git_dir.path) # Get the pull requests remote_repo = git.remote.url.split(':')[1] repo_owner, repo = remote_repo.split('/') repo = repo.gsub(/\.git$/, '') puts "Requesting PR list" config = YAML.load_file(File.expand_path "~/.env.yml") base_url = config["github_base_url"] || "https://github.com" api_base_url = config["github_api_base_url"] || "https://api.github.com" github = Github.new(user: repo_owner, repo: repo, oauth_token: config["github_access_token"], site: base_url, endpoint: api_base_url) pulls = github.pull_requests.list # Find the pull request for the current branch puts "Matching for PR's on current branch" current_branch = git.current_branch my_pr = pulls.find {|p| p["head"]["label"] == "#{repo_owner}:#{current_branch}"} if my_pr puts "Found matching PR #{my_pr["number"]}" url = my_pr[:html_url] else puts "Didn't find a matching PR; opening up a prompt to open one" url = "#{base_url}/#{repo_owner}/#{repo}/compare/#{current_branch}?expand=1" end # Open in browser puts "URL: #{url}"
class ColleagueButton attr_accessor :state def initialize(caption) @caption = caption @state = nil end def mediator=(mediator) @mediator = mediator end def set_colleague_enabled(enabled) @state = enabled end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Talk, type: :model do before :each do @talk = Talk.new(title: 'opening speech 2', description: 'orem ipsum dolor sit amet, consectetur adipiscing, elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat', startTime: 'DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 2)', endTime: 'DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1', location: 'hall 1', speakers: ['speaker 1']) end context 'valid Talk' do it 'has a valid title' do expect(@talk).to be_valid end it 'has a valid startTime' do expect(@talk).to be_valid end it 'has a valid location' do expect(@talk).to be_valid end it 'has a valid endTime' do expect(@talk).to be_valid end end context 'invalid Talk' do it 'has a invalid title' do @talk.title = ' ' expect(@talk).to_not be_valid end it 'has a invalid location' do @talk.location = ' ' expect(@talk).to_not be_valid end it 'has a invalid startTime' do @talk.startTime = ' ' expect(@talk).to_not be_valid end it 'has a invalid endTime' do @talk.endTime = ' ' expect(@talk).to_not be_valid end it 'has a unique email' do talk = Talk.new(title: 'opening speech 2', startTime: 'DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 2)', endTime: 'DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1', location: 'hall 1', speakers: ['speaker 1']) @talk.save expect(talk).to_not be_valid end end end
class Restaurant < ActiveRecord::Base belongs_to :vendor has_many :deals has_attached_file :image, styles: { medium: "300x300>"} do_not_validate_attachment_file_type :image validates_presence_of :name validates_presence_of :description validates_presence_of :phone validates_presence_of :email validates_presence_of :address validates_presence_of :image end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :playlist do url "MyString" order 1.5 end end
class Path < ActiveRecord::Base belongs_to :route validates :route, presence: true end
# frozen_string_literal: true module VmTranslator module Commands class Or def ==(other) self.class == other.class end def accept(visitor) visitor.visit_or(self) end end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # Set the locale, default is en-US Faker::Config.locale = 'ja' 10.times do user_name = Faker::Name.name_with_middle user_email = Faker::Internet.email(user_name.split(' ')[0]) user_pass = Faker::Internet.password(5, 20) User.create( name: user_name, email: user_email, password: user_pass, password_confirmation: user_pass ) end
module RSence module ArgvUtil # Main argument parser for the status command, sends the INFO (or PWR on linux) POSIX signal to # the process, if running. # Checks if the process responds on the port and address it's configured for. def parse_status_argv init_args expect_option = false option_name = false if @argv.length >= 2 @argv[1..-1].each_with_index do |arg,i| if expect_option if [:port].include?(option_name) and arg.to_i.to_s != arg puts ERB.new( @strs[:messages][:invalid_option_expected_number] ).result( binding ) exit elsif option_name == :conf_files if not File.exists?( arg ) or not File.file?( arg ) puts ERB.new( @strs[:messages][:no_such_configuration_file] ).result( binding ) exit else @args[:conf_files].push( arg ) end else @args[option_name] = arg end expect_option = false else if arg.start_with?('--') if arg == '--debug' set_debug elsif arg == '--verbose' set_verbose elsif arg == '--port' expect_option = true option_name = :port elsif arg == '--addr' expect_option = true option_name = :addr elsif arg == '--conf' or arg == '--config' expect_option = true option_name = :conf_files else invalid_option(arg) end elsif arg.start_with?('-') arg.split('')[1..-1].each do |chr| if chr == 'd' set_debug elsif chr == 'v' set_verbose else invalid_option(arg,chr) end end elsif valid_env?(arg) @args[:env_path] = File.expand_path(arg) @args[:conf_files].unshift( File.expand_path( File.join( arg, 'conf', 'config.yaml' ) ) ) else invalid_env( arg ) end end end if expect_option puts ERB.new( @strs[:messages][:no_value_for_option] ).result( binding ) exit end end if valid_env?(@args[:env_path]) conf_file = File.expand_path( File.join( @args[:env_path], 'conf', 'config.yaml' ) ) @args[:conf_files].unshift( conf_file ) unless @args[:conf_files].include?( conf_file ) else invalid_env end require 'rsence/default_config' require 'socket' config = Configuration.new(@args).config port = config[:http_server][:port] addr = config[:http_server][:bind_address] port_status = [] if addr == '0.0.0.0' and Socket.respond_to?(:ip_address_list) Socket.ip_address_list.each do |if_addr| if test_port( port, if_addr.ip_address ) port_status.push( if_addr.ip_address ) end end else port_status.push( addr ) end addr_descr = port_status.join(":#{port}, ")+":#{port}" if RSence.pid_support? pid_fn = config[:daemon][:pid_fn] if File.exists?( pid_fn ) pid = File.read( pid_fn ).to_i sig_name = RSence.info_signal_name pid_status = RSence::SIGComm.wait_signal_response( pid, pid_fn, sig_name, 3 ) else warn @strs[:messages][:no_pid_file] if @args[:verbose] pid_status = nil end else warn @strs[:messages][:no_pid_support] if @args[:verbose] pid_status = nil end addr_descr = port_status.join(":#{port} and ")+":#{port}" unless port_status.empty? if not RSence.pid_support? or pid_status == nil if RSence.pid_support? puts @strs[:messages][:no_pid] else puts @strs[:messages][:no_pid_support] end unless port_status.empty? puts ERB.new( @strs[:messages][:something_responds] ).result( binding ) end elsif pid_status == false if port_status.empty? puts ERB.new( @strs[:messages][:no_process_running_and_nothing_responds] ).result( binding ) else puts ERB.new( @strs[:messages][:no_process_running_but_something_responds] ).result( binding ) end else if port_status.empty? puts ERB.new( @strs[:messages][:process_running_but_nothing_responds] ).result( binding ) else addr_descr = port_status.join(":#{port} and ")+":#{port}" puts ERB.new( @strs[:messages][:process_running_and_responds] ).result( binding ) end end end end end
require "#{Rails.root}/app/operation_models/url_service.rb" module Api module V1 class UrlsController < ActionController::API $instance=Urloperation.new def getall shorturls = $instance.getall render json: {status: 'SUCCESS', message:'Loaded Urls', data:shorturls},status: :ok end def create shorturls = $instance.create(url_params) if(shorturls=="taken") render json: {status: 'ERROR', message:'this Url is taken ', data:[]},status: :unprocessable_entity else if(shorturls.errors.empty?) render json: {status: 'SUCCESS', message:'Saved Url', data:shorturls},status: :ok else render json: {status: 'ERROR', message:'Url not saved', data:shorturls.errors},status: :unprocessable_entity end end end def general #{request.protocol}#{request.host_with_port}#{request.fullpath} #var=request.fullpath.sub('/', '') test= $instance.get_by_urlnew(url_input[:newurl].to_s) if(test=="not found") # redirect_to "#{Rails.root}/public/404.html" render json: {status: 'ERROR ', message:'not found 404 ', data:[]},status: :unprocessable_entity else render json: {status: 'SUCCESS', message:'get Url', data: test },status: :ok end #@geturl=request.original_url #redirect_to @geturl end def url_params params.permit(:originalurl, :newurl) end def url_input params.permit(:newurl) end end end end
# Run me with `rails runner db/data/20230614151054_correct_partner_org_identifiers.rb` # Two partner org identifiers need correcting, as per this Zendesk ticket https://dxw.zendesk.com/agent/tickets/17993. # This is a one-off task. changes = [ { existing_partner_organisation_identifier: "_ES/X014088/1", new_partner_organisation_identifier: "ES/X014088/1" }, { existing_partner_organisation_identifier: "_ES/X014037/1", new_partner_organisation_identifier: "ES/X014037/1" } ] changes.each do |change| activity = Activity.find_by(partner_organisation_identifier: change.fetch(:existing_partner_organisation_identifier)) puts "BEFORE: Activity #{activity.id} initially has partner organisation identifier: #{activity.partner_organisation_identifier}" activity.partner_organisation_identifier = change.fetch(:new_partner_organisation_identifier) activity.save! activity.reload puts "AFTER: Activity #{activity.id} now has partner organisation identifier: #{activity.partner_organisation_identifier}" end
require 'rails_helper' describe IndexParser do describe 'start' do context 'when parsing the file' do subject do described_class.start end it 'should create new packages' do VCR.use_cassette('index_parser/package_file') do expect { subject }.to change(Package, :count) end end end end end
# frozen_string_literal: true require 'test_helper' class TeacherSetsHelperTest < ActiveSupport::TestCase extend Minitest::Spec::DSL include LogWrapper include TeacherSetsHelper before do @teacher_set = TeacherSet.new @mintest_mock1 = MiniTest::Mock.new @mintest_mock2 = MiniTest::Mock.new end describe 'Get var field data from request body' do it 'test var-field method' do self.instance_variable_set(:@req_body, SIERRA_USER["data"][0]) assert_equal("physical desc", var_field_data('300', true)) end it 'test var-field method with content' do self.instance_variable_set(:@req_body, SIERRA_USER["data"][0]) assert_equal("physical desc", var_field_data('300', false)) end it 'test var-field method with req_body nil' do self.instance_variable_set(:@req_body, nil) assert_equal(nil, var_field_data('300')) end end describe 'Get all_var_fields data from request body' do it 'test all_var_fields method' do self.instance_variable_set(:@req_body, SIERRA_USER["data"][0]) assert_equal(["physical desc"], all_var_fields('300')) end it 'test all_var_fields method with req_body nil' do self.instance_variable_set(:@req_body, nil) assert_nil(all_var_fields('300')) end end describe 'test grade value method' do it 'test pre-k and K grades' do assert_equal(0, grade_val('K')) assert_equal(-1, grade_val('PRE K')) assert_equal(1, grade_val(1)) end end describe 'Get fixed_field data from request body' do it 'test fixed_field method with req_body' do self.instance_variable_set(:@req_body, SIERRA_USER["data"][0]) assert_equal("English", fixed_field('44')) end it 'test fixed_field method with req_body nil' do self.instance_variable_set(:@req_body, nil) assert_nil(fixed_field('44')) end end describe 'test grades' do it 'test grades from prek to 12' do grades = ["3-8"] assert_equal(grades, get_grades(grades)) end it 'test unknown grades' do grades = ["14"] assert_equal([-1], get_grades(grades)) grades = ["1-14"] assert_equal(["1"], get_grades(grades)) grades = ["14-2"] assert_equal(["2"], get_grades(grades)) end end describe 'return teacher-set grades' do # Test1 it 'test teacher_set grades' do self.instance_variable_set(:@req_body, SIERRA_USER["data"][0]) return_grades = %w[3 8] assert_equal(return_grades, grade_or_lexile_array('grade')) end end end
require 'optparse' require 'yaml' class Options def self.parse options = {} optparse = OptionParser.new do |opts| # Set a banner, displayed at the top of the help screen. opts.banner = "Usage: jifu [-f UPLOAD_FOLDER, -n NAME_FOLDER, -u USERNAME, -p PASSWORD] file1 file2 ..." config = YAML.load_file(File.join(File.dirname(__FILE__), 'config.yml')) options[:name_folder] = config['name_folder'] options[:username] = config['username'] options[:password] = config['password'] options[:upload_folder] = nil opts.on( '-f', '--folder UPLOAD_FOLDER', 'Specifies folder where all files are uploaded - REQUIRED' ) do |upload_folder| options[:upload_folder] = upload_folder end opts.on( '-n', '--full_name NAME_FOLDER', 'Specifies full name folder on site - not required if specified in config.yml' ) do |name_folder| options[:name_folder] = name_folder end opts.on( '-u', '--username USERNAME', 'Specifies login username - not required if specified in config.yml' ) do |username| options[:username] = username end opts.on( '-p', '--password PASSWORD', 'Specifies login password - not required if specified in config.yml' ) do |password| options[:password] = password end # This displays the help screen, all programs are assumed to have this option. opts.on( '-h', '--help', 'Display this screen' ) do puts opts puts "\nNote: specifying `.` will use all files in the current folder" exit end end files = optparse.parse!.uniq if options.has_value? nil puts 'WARNING MISSING CONFIG. Please include a folder, full name, username and password in either config.yml or as a command line argument' #exit end # Include whole folder if files.include? '.' files = files + Dir.entries(".") files = files - ['.', '..'] end # Remove files starting with `.` or `~`, replace them with their full paths and get rid of dups options[:files] = files.select { |file| !(file.start_with?('.') || file.start_with?('~'))}.map { |file| File.join(Dir.getwd, file) }.uniq return options end end #puts Options.parse
class Announcement < ActiveRecord::Base acts_as_paranoid attr_accessible :course_id, :creator_id, :description, :important, :publish_at, :title scope :published, lambda { where("publish_at <= ? ", Time.now) } belongs_to :course belongs_to :creator, class_name: "User" end
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0) # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # confirmation_token :string(255) # confirmed_at :datetime # confirmation_sent_at :datetime # unconfirmed_email :string(255) # created_at :datetime not null # updated_at :datetime not null # name :string(255) # class User < ActiveRecord::Base rolify # Include default devise modules. Others available are: # :token_authenticatable, :confirmable , # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :email_regexp => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i has_many :user_courseships, :dependent => :delete_all has_many :courses, :through => :user_courseships # Setup accessible (or protected) attributes for your model attr_accessible :name, :email, :role_ids, :as => :admin attr_accessible :name, :email, :password, :password_confirmation, :remember_me validates :name, :presence => true, :length => { :minimum => 2, :maximum => 50 }, :uniqueness => true validates :email, :presence => true, :format => { with: Devise.email_regexp }, :uniqueness => { case_sensitive: false } validates :password, :confirmation => true def follow!(course) user_courseships.create!(:course_id => course.id) end def following?(course) user_courseships.find_by_course_id(course) end def unfollow!(course) user_courseships.find_by_course_id(course).destroy end end
require 'gosu' require 'opengl' require 'glu' OpenGL.load_lib GLU.load_lib include OpenGL, GLU require_relative 'gl_texture.rb' require_relative 'tiled_optimizer.rb' class Window < Gosu::Window def initialize super(640, 480, false) @tiled_map = TiledMap.new('tiled_maps/test.json') @x, @y, @z = 0, 30, 100 @t_x, @t_y, @t_z = 0, 10, 0 end def button_down(id) close! if id == Gosu::KB_ESCAPE end def needs_cursor?; true; end def update v = 1 if Gosu::button_down?(Gosu::KB_W) @z -= v @t_z -= v elsif Gosu::button_down?(Gosu::KB_S) @z += v @t_z += v elsif Gosu::button_down?(Gosu::KB_A) @x -= v @t_x -= v elsif Gosu::button_down?(Gosu::KB_D) @x += v @t_x += v end end def draw gl do glEnable(GL_DEPTH_TEST) glEnable(GL_TEXTURE_2D) glMatrixMode(GL_PROJECTION) glLoadIdentity gluPerspective(45, self.width.to_f / self.height, 1, 1000) glMatrixMode(GL_MODELVIEW) glLoadIdentity gluLookAt(@x, @y, @z, @t_x, @t_y, @t_z, 0, 1, 0) @angle ||= 0 @angle += 0.2 glRotatef(@angle, 0, 1, 0) @tiled_map.draw end end end Window.new.show
module Git::Webby module HttpBackendHelpers #:nodoc: include GitHelpers def service_request? not params[:service].nil? end # select_service feature def service @service = params[:service] return false if @service.nil? return false if @service[0, 4] != "git-" @service = @service.gsub("git-", "") end # pkt_write feature def packet_write(line) (line.size + 4).to_s(16).rjust(4, "0") + line end # pkt_flush feature def packet_flush "0000" end # hdr_nocache feature def header_nocache headers "Expires" => "Fri, 01 Jan 1980 00:00:00 GMT", "Pragma" => "no-cache", "Cache-Control" => "no-cache, max-age=0, must-revalidate" end # hdr_cache_forever feature def header_cache_forever now = Time.now headers "Date" => now.to_s, "Expires" => (now + 31536000).to_s, "Cache-Control" => "public, max-age=31536000" end # select_getanyfile feature def read_any_file unless settings.get_any_file halt 403, "Unsupported service: getanyfile" end end # get_text_file feature def read_text_file(*file) read_any_file header_nocache content_type "text/plain" repository.read_file(*file) end # get_loose_object feature def send_loose_object(prefix, suffix) read_any_file header_cache_forever content_type_for_git :loose, :object send_file(repository.loose_object_path(prefix, suffix)) end # get_pack_file and get_idx_file def send_pack_idx_file(pack, idx = false) read_any_file header_cache_forever content_type_for_git :packed, :objects, (idx ? :toc : nil) send_file(repository.pack_idx_path(pack)) end def send_info_packs read_any_file header_nocache content_type "text/plain; charset=utf-8" send_file(repository.info_packs_path) end # run_service feature def run_advertisement(service) header_nocache content_type_for_git service, :advertisement response.body.clear response.body << packet_write("# service=git-#{service}\n") response.body << packet_flush response.body << repository.run(service, "--stateless-rpc --advertise-refs .") response.finish end def run_process(service) content_type_for_git service, :result input = request.body.read command = repository.cli(service, "--stateless-rpc #{git.repository}") # This source has extracted from Grack written by Scott Chacon. IO.popen(command, File::RDWR) do |pipe| pipe.write(input) while !pipe.eof? block = pipe.read(8192) # 8M at a time response.write block # steam it to the client end end # IO response.finish end end # HttpBackendHelpers # The Smart HTTP handler server. This is the main Web application which respond to following requests: # # <repo.git>/HEAD :: HEAD contents # <repo.git>/info/refs :: Text file that contains references. # <repo.git>/objects/info/* :: Text file that contains all list of packets, alternates or http-alternates. # <repo.git>/objects/*/* :: Git objects, packets or indexes. # <repo.git>/upload-pack :: Post an upload packets. # <repo.git>/receive-pack :: Post a receive packets. # # See ::configure for more details. class HttpBackend < Application set :authenticate, true set :get_any_file, true set :upload_pack, true set :receive_pack, false helpers HttpBackendHelpers before do authenticate! if settings.authenticate end # implements the get_text_file function get "/:repository/HEAD" do read_text_file("HEAD") end # implements the get_info_refs function get "/:repository/info/refs" do if service_request? # by URL query parameters run_advertisement service else read_text_file(:info, :refs) end end # implements the get_text_file and get_info_packs functions get %r{/(.*?)/objects/info/(packs|alternates|http-alternates)$} do |repository, file| if file == "packs" send_info_packs else read_text_file(:objects, :info, file) end end # implements the get_loose_object function get %r{/(.*?)/objects/([0-9a-f]{2})/([0-9a-f]{38})$} do |repository, prefix, suffix| send_loose_object(prefix, suffix) end # implements the get_pack_file and get_idx_file functions get %r{/(.*?)/objects/pack/(pack-[0-9a-f]{40}.(pack|idx))$} do |repository, pack, ext| send_pack_idx_file(pack, ext == "idx") end # implements the service_rpc function post "/:repository/:service" do run_process service end private helpers AuthenticationHelpers end # HttpBackendServer end # Git::Webby
require 'singleton' module Kilomeasure class MeasuresRegistry include Singleton attr_accessor :loader def self.get(name) instance.get(name) end def self.load(data_path: nil) instance.loader.data_path = data_path if data_path instance.load_measures end def self.reset instance.reset end def self.set(name, data) instance.set(name, data) end def initialize(**options) construct(options) end def all load_measures @measures_lookup.select { |_key, value| value.present? }.values end def get(name) @measures_lookup[name] ||= load_measure(name) end def has_measure?(name) @measures_lookup.has_key?(name) end def load_measures loader.each_measure_from_file do |measure| @measures_lookup[measure.name] = measure end end def loaded? !@measures_lookup.empty? end def names all.map(&:name) end def reset construct end def set(name, data) @measures_lookup[name] = loader.load_from_data(name, data) end private # For reuse in reset method def construct(loader: nil) loader ||= MeasureLoader.new @loader = loader @measures_lookup = HashWithIndifferentAccess.new end def load_measure(name) loader.load_from_file(name) end end end
# frozen_string_literal: true require 'spec_helper' describe RubyPx::Dataset do let(:subject) { described_class.new 'http://populate-data.s3.amazonaws.com/ruby_px/f1.px' } describe '#headings' do it 'should return the list of headings described in the file' do expect(subject.headings).to eq(['Fenómeno demográfico']) end end end
class CreateInterfaces < ActiveRecord::Migration def self.up create_table :interfaces, :id => false do |t| t.string :type, :limit=>'128' t.string :name, :limit=>'1024' t.string :description, :limit=>'4096' t.string :ikey, :limit=>'1024' t.string :filename, :limit=>'4096' t.string :syntax, :limit=>'4096' t.string :hostname, :limit=>'256' end end def self.down drop_table :interfaces end end
class Question < ActiveRecord::Base belongs_to :user has_one :topic has_many :comments acts_as_friendly_param :headline validates_presence_of :headline validates_presence_of :body acts_as_taggable cattr_reader :per_page @per_page = 25 HUMANIZED_ATTRIBUTES = { :headline => "Question", :body =>'Details' } def self.human_attribute_name(attr) HUMANIZED_ATTRIBUTES[attr.to_sym] || super end def self.findanswers(questionid) @sql ="select count(rating) rating,questionid,parentid,questions.id id,questions.created_at created_at,body,"+ "questions.user_id,questions.headline,questions.correct_flag from ratings right join questions on " + "questionid = questions.id where parentid="+ questionid + " and correct_flag = 0 group by(id)order by rating desc" Question.find_by_sql(@sql) end def self.findcorrectanswers(questionid) @correctsql ="select count(rating) rating,questionid,parentid,questions.id id,questions.created_at created_at,body,"+ "questions.user_id,questions.headline,questions.correct_flag from ratings right join questions on " + "questionid = questions.id where parentid="+ questionid + " and correct_flag = 1 group by(id)order by rating desc" Question.find_by_sql(@correctsql) end def self.top_questions @topsql = 'select count(rating) rating,questionid,parentid,questions.id id,questions.created_at created_at,body,'+ 'questions.user_id,questions.headline,questions.correct_flag,topic_id '+ 'from ratings right join questions on questionid = questions.id where parentid =0 group by(id)order by rating desc' Question.find_by_sql(@topsql) end def self.findparent(id) @parentsql = 'select * from questions where id=' + id.to_s Question.find_by_sql(@parentsql) end def recent(options = {}) limit = options[:limit] || 15 returning([]) do |collection| collection << Post.recent.all(:limit => limit) collection << Questions.recent.all(:limit => limit) collection << User.recent.all(:limit => limit) end.flatten.sort_by(&:updated_at).reverse.slice(0, limit) end end
require 'formula' class Repl < Formula homepage 'https://github.com/defunkt/repl' url 'https://github.com/defunkt/repl/archive/v1.0.0.tar.gz' sha1 'd47d31856a0c474daf54707d1575b45f01ef5cda' depends_on 'rlwrap' => :optional def install bin.install 'bin/repl' man1.install 'man/repl.1' end end
class Player < ActiveRecord::Base self.table_name = "pong_player" def self.merge_default_parameters(player_params) player_params.merge( { wins: 0, losses: 0, random_token: PasswordDigester.generate_token }) end def update_attributes_with_encrypted_password(player_params) self.update_attributes( name: player_params[:name], login: player_params[:login], password: PasswordDigester.encrypt( player_params[:password] ) ) end def correct_password?(entered_password) PasswordDigester.check?( entered_password, self.password ) end def update_wins_losses self.update_columns( wins: Match.where(match_winner_id: id).size, losses: Match.where(match_loser_id: id).size ) end end
module MessageCenter module Concerns module Models autoload :Conversation, 'concerns/models/conversation' autoload :Item, 'concerns/models/item' autoload :Mailbox, 'concerns/models/mailbox' autoload :Message, 'concerns/models/message' autoload :Notification, 'concerns/models/notification' autoload :Receipt, 'concerns/models/receipt' end end module Models autoload :Messageable, 'message_center/models/messageable' end mattr_accessor :messageable_class @@messageable_class = 'User' mattr_accessor :default_from @@default_from = 'no-reply@message_center.com' mattr_accessor :uses_emails @@uses_emails = true mattr_accessor :use_mail_dispatcher @@use_mail_dispatcher = true mattr_accessor :mailer_wants_array @@mailer_wants_array = false mattr_accessor :search_enabled @@search_enabled = false mattr_accessor :search_engine @@search_engine = :solr mattr_accessor :email_method @@email_method = :message_center_email mattr_accessor :name_method @@name_method = :name mattr_accessor :subject_max_length @@subject_max_length = 255 mattr_accessor :body_max_length @@body_max_length = 32000 mattr_accessor :notification_mailer mattr_accessor :message_mailer mattr_accessor :custom_deliver_proc class << self def setup yield self end end end require 'message_center/engine' require 'message_center/service' require 'message_center/cleaner' require 'message_center/mail_dispatcher'
class KwkFulfillmentMailerPreview < ActionMailer::Preview def shipping KwkFulfillmentMailer.shipping(KwkFulfillment.with_shipping_state.last) end end
require 'mongoid' class SchemaField include Mongoid::Document field :id field :name field :data_type field :required, :type => Boolean embedded_in :list validates :name, :presence => true end
# frozen_string_literal: true RSpec.describe NilLocalCampaign do let(:campaign) { described_class.new } %i[external_reference status description].each do |attr| describe "##{attr}" do subject { campaign.send(attr) } it { is_expected.to eq 'Non Existent' } end end end
require File.dirname(__FILE__) + '/../spec_helper.rb' require 'action_controller' require 'action_controller/assertions/selector_assertions' include ActionController::Assertions::SelectorAssertions describe MifToHtmlParser do before(:all) do Act.stub!(:from_name).and_return nil end def parser url=nil, other_url=nil parser = MifToHtmlParser.new parser.stub!(:find_act_url).and_return url parser.stub!(:find_bill_url).and_return other_url parser end describe 'when parsing Clauses MIF XML file to text' do before(:all) do @result = parser.parse_xml(fixture('clauses.xml'), :format => :text) end it 'should not have any tags in output' do @result.should include('Be it enacted by the Queen’s most Excellent Majesty, by &amp; with the advice and consent of the Lords Spiritual and Temporal, and Commons, in this present Parliament assembled, and by the authority of the same, as follows:—') end end describe 'when parsing Clauses MIF XML file to haml' do before(:all) do @result = parser.parse_xml(fixture('clauses.xml'), :format => :haml) end it 'should not put Para span before _Paragraph_PgfTag paragraph' do @result.should_not include("%span#1112895.Para") @result.should include("#1112895.Para") end it 'should have an anchor name marking a clause start' do @result.should include(%Q|%span.PgfNumString_1<>\n %a#clause_LC1{ :name => \"clause1\", :href => \"#clause1\" }<>\n 1\n|) end it 'should have toggle link around clause title' do @result.should include(%Q|= link_to_function "Reports on implementation of Law Commission proposals", "$('#1112590').toggle();imgswap('1112590_img')"|) end it 'should have clause-page-line and page-line anchors' do @result.should include('%a{ :name => "page1-line10" }') @result.should include('%a{ :name => "page1-line15" }') @result.should include('%a{ :name => "clause1-page1-line10" }') @result.should include('%a{ :name => "clause1-page1-line15" }') end end describe 'when parsing another MIF XML file to html' do before(:all) do @result = parser.parse_xml(fixture('pbc0850206m.xml'), :format => :html) end it 'should create html' do @result.should have_tag('html') @result.should have_tag('div[class="Resolution"][id="1070180"]') do with_tag('div[class="ResolutionHead"][id="1070184"]') do with_tag('p[class="OrderHeading_PgfTag"][id="7335998"]', :text => 'Resolution of the Programming Sub-Committee') end end @result.should have_tag('table[class="TableData"][id="7336058"]') do with_tag('tr[id="6540534"]') do with_tag('th[id="6540535"]', :text => 'Date') with_tag('th[id="6540536"]', :text => 'Time') with_tag('th[id="6540537"]', :text => 'Witness') end with_tag('tr[class="Row"][id="6540538"]') do with_tag('td[id="6540539"]', :text => 'Tuesday 2 June') with_tag('td[id="6540540"]', :text => 'Until no later than 12 noon') with_tag('td[id="6540541"]', :html => 'Equality and Diversity Forum<br />Equality and Human Rights Commission<br />Employment Tribunals Service') end end end it 'should put anchor before span' do @result.should have_tag('a[name="page29-line24"]') @result.should have_tag('span[id="1485163"][class="Number"]', :text => 'Clause 1,') do with_tag('span[class="Clause_number"]', :text=>'1') end end it 'should make clause/page/line reference a hyperlink' end describe 'when parsing longer MIF XML file to html' do before(:all) do @result = parser.parse_xml(fixture('pbc0900206m.xml'), :format => :html) end it 'should create html' do @result.should have_tag('html') @result.should have_tag('div[class="Committee"][id="5166572"]') do with_tag('div[class="Clause_Committee"][id="2494674"]') do with_tag('ul[class="Sponsors"][id="2494677"]') do with_tag('li[class="Sponsor"][id="2494680"]', :text => 'Mr Jeremy Browne') end end with_tag('div[class="Amendment_Text"][id="2494721"]') do with_tag('div[class="SubSection"][id="7316809"]') do with_tag('p[class="SubSection_PgfTag"][id="7332538"]', :text => '‘(1) Aircraft flight duty is chargeable in respect of each freight and passenger aircraft on each flight undertaken by that aircraft from a destination within the UK.’.') do with_tag('span[class="PgfNumString"]', :text => '‘(1)') end end end end @result.should have_tag('div[class="Para_sch"][id="1085999"]') do with_tag('div[class="SubPara_sch"]') do with_tag('p[class="SubParagraph_sch_PgfTag"][id="7381591"]') do with_tag('span[class="PgfNumString"]') do with_tag('span[class="PgfNumString_1"]', :text => 'A2') with_tag('span[class="PgfNumString_2"]', :text => '(1)') end with_tag('span[class="SubPara_sch_text"]', :text => 'Paragraph 1(2) (application of Schedule) is amended as follows.') end end with_tag('p[class="SubParagraphCont_sch_PgfTag"][id="7381594"]') do with_tag('span[class="PgfNumString"]') do with_tag('span[class="PgfNumString_1"]', :text => '&nbsp;') with_tag('span[class="PgfNumString_2"]', :text => '(2)') end end end @result.should have_tag('div[class="SubPara_sch"][id="1090948"]') do with_tag('p[class="SubParagraph_sch_PgfTag"][id="7381591"]') do with_tag('span[class="PgfNumString"]', :text =>'A2 (1)') with_tag('span[class="SubPara_sch_text"]', :text => 'Paragraph 1(2) (application of Schedule) is amended as follows.') end end end end describe 'when parsing a standing committee MIF XML file to html' do before(:all) do @url = 'http://www.opsi.gov.uk/acts/acts1992/ukpga_19920004_en_1' @result = parser(@url,nil).parse_xml(fixture('CommA20031218DummyFM7.xml'), :format => :html) end it 'should put new line anchor outside of citation link' do @result.should have_tag('p[id="1055416"][class="Paragraph_PgfTag"]') do with_tag('span[class="Para_text"]') do with_tag('a[id="1055415"][class="Citation"][href="' + @url + '"]', :text => 'Social Security Contributions and Benefits Act 1992 (c. 4)') with_tag('a[name="page14-line7"]') end end @result.should_not include('<a id="1055415" href="' + @url + '" class="Citation">Social Security Contributions and <a name="page14-line7"></a>Benefits Act 1992 (c. 4)</a>') @result.should include('<a id="1055415" href="' + @url + '" class="Citation" title="Social Security Contributions and Benefits Act 1992 (c. 4)">Social Security Contributions and <br />Benefits Act 1992 (c. 4)</a><a name="page14-line7"></a>') end it 'should put new line anchor outside of Shorttitle link' do @result.should include('<a name="page1-line5"></a><div id="1045605" class="Shorttitle">Child Trust Funds Bill</div>') end end describe 'when parsing another standing committee MIF XML file to html' do before(:all) do @url = 'http://www.opsi.gov.uk/acts/acts1992/ukpga_19920004_en_1' @result = parser(@url).parse_xml(fixture('CommA20031229DummyFM7.xml'), :format => :html) File.open(RAILS_ROOT + '/spec/fixtures/CommA20031229DummyFM7.html','w') {|f| f.write @result } end it 'should add a br when there is a new line in a Amendment_Text_text span, and make SoftHyphen a hyphen' do @result.should include('<span class="Amendment_Text_text">after second ‘the’, insert ‘first day of the month that in-<br /><a name="page5-line18"></a>cludes the’.</span></p>') end it 'should add a br when new line occurs in an Italic span' do @result.should include('<span class="Italic" id="1051524">reduction of age of <br /><a name="page5-line35"></a>majority in respect of child trust funds</span>') end it 'should not restart _text span when it encloses an Italic span' do italicized = 'reduction of age of majority in respect of child trust funds' text = "‘(2) Section [#{italicized}] extends to Northern Ireland, but does not extend to Scotland.’." @result.should have_tag('div[class="SubSection"][id="1051587"]') do with_tag('p[class="SubSection_PgfTag"][id="1051592"]') do with_tag('span[class="SubSection_text"]', :text => text) do with_tag('span[class="Italic"][id="1051590"]', :text => italicized) end end end end end describe 'when parsing a bill with citation to act' do before(:all) do @url = 'http://www.opsi.gov.uk/acts/acts2005/ukpga_20050014_en_14' @result = parser(@url).parse_xml(fixture('ChannelTunnel/ChannelTunnelClauses.act.xml'), :format => :haml) File.open(RAILS_ROOT + '/spec/fixtures/ChannelTunnel/ChannelTunnelClauses.haml','w') {|f| f.write @result } end it 'should put space after page anchor when citation is at start of line' do @result.should include('\ from being exercised in relation to the rail link or railway services on it.') end it 'should put line start anchor outside of section reference anchor' do @result.should include(' section 6 of the Railways Act 2005 %br (c. 14) %a{ :name => "page1-line12" }<> %a{ :name => "clause1-page1-line12" }<>') end end describe 'when parsing a Lords Clauses MIF XML file to html' do before(:all) do @result = parser.parse_xml(fixture('DigitalEconomy/Clauses.act.xml'), :format => :html) end it 'should create html' do @result.should have_tag('html') @result.should have_tag('div[class="Clauses"][id="1112573"]') end it 'should not create a named anchor inside Prelim section' do @result.should have_tag('div[class="Prelim"][id="1112587"]') do with_tag('div[class="ABillTo"][id="1003906"]') do with_tag('div[class="Abt1"][id="1003909"]') do without_tag('a[name]') end end end end it 'should create line break when line break is between xrefs' do @result.should include('<a id="1144999" class="Xref" href="#clause13-amendment-clause124J-2-a" title="Clause 13, Amendment Clause 124J Subsection 2 paragraph a">(a)</a><br /><a name="page15-line7"></a><a name="clause13-page15-line7"></a>or <a id="1145003" class="Xref" href="#clause13-amendment-clause124J-2-c" title="Clause 13, Amendment Clause 124J Subsection 2 paragraph c">(c)</a>') end it 'should create a named anchor for page1-line1 inside the first CrossHeading section' do @result.should have_tag('div[class="CrossHeading"][id="1112628"]') do with_tag('div[class="CrossHeadingTitle"][id="1113244"]') do with_tag('a[name="page1-line1"]') end end end end describe 'when parsing Schedules MIF XML file to html' do before(:all) do @result = parser.parse_xml(fixture('DigitalEconomy/example/Schedules_example.xml'), :format => :html) end it 'should create html' do @result.should have_tag('html') @result.should have_tag('div[class="Schedules"][id="1061327"]') do with_tag('div[class="SchedulesTitle"][id="1061360"]') with_tag('div[class="Schedule"][id="1059032"]') do with_tag('p[class="ScheduleNumber_PgfTag"][id="1061375"]') do with_tag('span[class="PgfNumString"]') do with_tag('span[class=PgfNumString_0]', :text => 'Schedule 1') end end with_tag('div[class="SectionReference"][id="1059060"]') with_tag('div[class="ScheduleTitle"][id="1059046"]') with_tag('div[class="ScheduleText"][id="1059046t"]') do with_tag('div[class="Para_sch"][id="1059118"]') end end end end it 'should put anchor before span' do @result.should have_tag('p[class="SubSubParagraph_sch_PgfTag"][id="1202341"]') do with_tag('a[name="page53-line1"]') with_tag('span[class="SubSubPara_sch_text"]', :text => 'after “Act” insert—') end end end end
require 'test_helper' class Piece10sControllerTest < ActionController::TestCase setup do @piece10 = piece10s(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:piece10s) end test "should get new" do get :new assert_response :success end test "should create piece10" do assert_difference('Piece10.count') do post :create, piece10: { name: @piece10.name, user_id: @piece10.user_id } end assert_redirected_to piece10_path(assigns(:piece10)) end test "should show piece10" do get :show, id: @piece10 assert_response :success end test "should get edit" do get :edit, id: @piece10 assert_response :success end test "should update piece10" do patch :update, id: @piece10, piece10: { name: @piece10.name, user_id: @piece10.user_id } assert_redirected_to piece10_path(assigns(:piece10)) end test "should destroy piece10" do assert_difference('Piece10.count', -1) do delete :destroy, id: @piece10 end assert_redirected_to piece10s_path end end
require 'spec_helper' describe Rounders do it 'has a version number' do expect(Rounders::VERSION).not_to be nil end describe '.global?' do context 'when app directory not exists' do before do allow_any_instance_of(Pathname).to receive(:exist?).and_return(false) end it 'should return false' do expect(Rounders.global?).to be_truthy end end context 'when app directory exists' do before do allow_any_instance_of(Pathname).to receive(:exist?).and_return(true) end it 'should return true' do expect(Rounders.global?).to be_falsey end end end end
class Payment < ActiveRecord::Base belongs_to :loan validate :must_be_valid_amount def must_be_valid_amount errors.add(:base, 'Payment must no be larger than the loan balance') unless payment_amount <= self.loan.balance end end
class CommentMailer < ApplicationMailer def comment_created(user, comment) @user = user @comment = comment @post = @comment.post @url = post_url(@post.id) @title = "New comment on: #{@post.title}" mail(to: @user.email, subject: @title) end end
# == Schema Information # # Table name: users # # id :bigint not null, primary key # name :string not null # email :string not null # password_digest :string not null # fullname :string # is_admin :boolean default(FALSE), not null # created_at :datetime not null # updated_at :datetime not null # class User < ApplicationRecord VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :name, presence: true, length: { maximum: 50 } validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: true before_validation :check_name before_validation :check_email has_secure_password validates :password, presence: true, length: { minimum: 4 } def User.find_and_authenticate(email, password) user = User.find_by(email: email.downcase) if user && user.authenticate(password) return user else return nil end end def User.digest(p) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(p, cost: cost) end def User.allIdNameUserExcept(user) User.select([:id, :name]).where.not(id: user.id) end private def trimAndLower!(str) if !str.nil? str.strip! str.downcase! end end def check_name trimAndLower!(name) end def check_email trimAndLower!(email) end end
class CreateLoyaltyConfigs < ActiveRecord::Migration def change create_table :loyalty_configs do |t| t.integer :multiple_per_euro, default: 100 t.integer :max_points, default: 20000 t.integer :points_time_limit,default: 2 t.integer :accumulation_speed_time_limit, default: 1 t.string :points_periode, default: "month" t.string :accumulation_periode, default: "month" t.integer :multiple_speed_offer, default: 2 t.timestamps end end end
require 'minitest/autorun' require_relative 'pet_shop_two' class PetShopTest < Minitest::Test def test_one_rat assert_equal ['B1'], Order.new(['R']).boxes end def test_one_hedgehog assert_equal ['B1'], Order.new(['H']).boxes end def test_one_mongoose assert_equal ['B2'], Order.new(['M']).boxes end def test_one_snake assert_equal ['B3'], Order.new(['S']).boxes end def test_rat_hedgehog_hedgehog assert_equal ['B3'], Order.new(['R', 'H', 'H']).boxes end def test_snake_mongoose assert_equal ['B2', 'B3'].sort, Order.new(['S', 'M']).boxes end def test_snake_hedgehog_rat_mongoose assert_equal ['B3', 'B3'].sort, Order.new(['S', 'H', 'R', 'M']).boxes end def test_rat_hedgehog_snake assert_equal ['B1', 'B3'].sort, Order.new(['R', 'H', 'S']).boxes end def test_disallow_other_aniomals assert_raises(ArgumentError) { Order.new(['X', 'Y', 'Z']) } end # extra tests def test_twenty_hedgehogs hedgehogs = [] 20.times{ hedgehogs.push('H') } assert_equal ['B3', 'B3', 'B3', 'B3', 'B3'].sort, Order.new(hedgehogs).boxes end def test_cricket assert_equal ['B0'].sort, Order.new(['C']).boxes end def test_two_crickets assert_equal ['B0'].sort, Order.new(['C', 'C']).boxes end def test_three_crickets assert_equal ['B1'].sort, Order.new(['C', 'C', 'C']).boxes end end
class FixColumnName < ActiveRecord::Migration def change rename_column :posts, :text, :description end end
class AccountsController < ApplicationController def new @account = Account.new(user: User.new) end def create @account = Account.new(account_params) user_pass = SecureRandom.hex(4) puts "=====> #{user_pass}" @account.user.password = user_pass @account.acc_id = SecureRandom.random_number(999999999999) @account.save end private def account_params params.require(:account).permit(:balance, :term_type, :deposit_term, user_attributes: [:id, :fullname, :NIC, :date_issue, :numberphone, :email, :address]) end end
class UsersController < ApplicationController before_action :set_user, only: %i[ show edit update destroy ] # GET /users or /users.json def index @users = User.all end # GET /users/1 or /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit end # POST /users or /users.json def create @user = User.new(user_params) respond_to do |format| if @user.save format.html { redirect_to signup_path, notice: "User was successfully created." } format.json { render :show, status: :created, location: signup_path } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PATCH/PUT /users/1 or /users/1.json def update respond_to do |format| if @user.update(user_params) format.html { redirect_to @user, notice: "User was successfully updated." } format.json { render :show, status: :ok, location: @user } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def rating if current_user != nil current_user.rated = true current_user.save end end def forget_password if params.include?(:forget_pw_username) && params.include?(:email_to_receive) user = User.find_by(username: params[:forget_pw_username]) if user user.login_token = create_token user.token_generated_at = Time.now.utc user.save #Used a email that we have accessed to, instead of the user's email in real life situation LoginTokenMailer.send_email(params[:email_to_receive], user.login_token, user.username).deliver redirect_to(root_path, :notice => 'Sent Temporary Login Link') else redirect_to forget_password_get_path, notice: 'Username not found' end end end # DELETE /users/1 or /users/1.json def destroy @user.destroy respond_to do |format| format.html { redirect_to users_url, notice: "User was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Only allow a list of trusted parameters through. def user_params params.require(:user).permit(:username, :email, :password, :password_confirmation) end def create_token SecureRandom.hex(10) end def token_validity 2.hours end end
class RegistrationsController < Devise::RegistrationsController protected def after_sign_up_path_for(resource) '/wikis' # '/charges/new' end end
Recaptcha.configure do |config| config.site_key = ENV['RECAPCHAUSER'] config.secret_key = ENV['RECAPCHASERVER'] # Uncomment the following line if you are using a proxy server: # config.proxy = 'http://myproxy.com.au:8080' end
actions :create, :delete, :dereg_instance, :reg_instance default_action :create attribute :lb_name, kind_of: String, name_attribute: true attribute :aws_access_key_id, kind_of: String, default: nil attribute :aws_secret_access_key, kind_of: String, default: nil attribute :region, kind_of: String, default: 'us-east-1' attribute :availability_zones, kind_of: Array, default: [] attribute :cross_zone_load_balancing, kind_of: [TrueClass, FalseClass], default: true attribute :connection_draining_enable, kind_of: [TrueClass, FalseClass], default: true attribute :connection_draining_timeout, kind_of: Integer, default: 300 attribute :subnet_ids, kind_of: Array, default: [] attribute :listeners, kind_of: Array, default: [{ 'InstancePort' => 80, 'Protocol' => 'HTTP', 'LoadBalancerPort' => 80 }] attribute :security_groups, kind_of: Array, default: [] attribute :instances, kind_of: Array, default: [] attribute :search_query, kind_of: String, default: '' attribute :timeout, kind_of: Integer, default: 60 attribute :health_check, kind_of: Hash, default: {} attribute :policies, kind_of: Hash, default: {} attribute :retries, kind_of: Integer, default: 20 attr_accessor :exists
# frozen_string_literal: true namespace :invoices do desc 'Process the event queue' task process_pagseguro: :environment do CheckPagseguroInvoicesJob.perform_now end end
class WebApi # Copyright Vidaguard 2013 # Author: Claudio Mendoza require "net/http" require "uri" require "net/https" require 'json' BOUNDARY = "AaB03x" def self.get(url) uri = URI.parse(url) # Shortcut response = Net::HTTP.get_response(uri) # Will print response.body puts Net::HTTP.get_print(uri) # Full http = Net::HTTP.new(uri.host, uri.port) response = http.request(Net::HTTP::Get.new(uri.request_uri)) end def self.authorize uri = URI.parse("http://127.0.0.1:3000") http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Get.new(uri.request_uri) request.basic_auth("username", "password") response = http.request(request) end def self.view_orders(acc_tok, ord_typ, vendor_id, patient_id = nil) uri = URI('http://127.0.0.1:3000/orders') params = { access_token: acc_tok, order_type: ord_typ, vendor_id: vendor_id, patient_id: patient_id } uri.query = URI.encode_www_form(params) response = Net::HTTP.get_response(uri) =begin ssl Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https').start do |http| request = Net::HTTP::Get.new uri.request_uri response = http.request request # Net::HTTPResponse object end =end puts response.body if response.is_a?(Net::HTTPSuccess) response end def self.assign_order(acc_tok, order_type, ancillary_id) uri = URI.parse("http://127.0.0.1:3000/orders") # Shortcut data = { order: { type: order_type, name: 'ABO' }, patient: { id: 2345, last_name: 'Jones', first_name: 'Paco', dob: '1982/12/22`' }, insurance: { name: 'United Health', member_id: '234567' }, visit: { room: '213', facility_id: 'location1' } } response = Net::HTTP.post_form(uri, data: data.to_json, access_token: acc_tok, ancillary_id: ancillary_id) JSON.parse(response.body) end def self.order_result(acc_tok, req_id) uri = URI.parse("http://127.0.0.1:3000/orders/#{req_id}") params = { access_token: acc_tok } uri.query = URI.encode_www_form(params) response = Net::HTTP.get_response(uri) #http = Net::HTTP.new(uri.host, uri.port) #request = Net::HTTP::Get.new(uri.request_uri) #response = http.request(request) response.body end def file_upload # Token used to terminate the file in the post body. Make sure it is not # present in the file you're uploading. uri = URI.parse("http://something.com/uploads") file = "/path/to/your/testfile.txt" post_body = [] post_body << "--#{BOUNDARY}rn" # post_body << "Content-Disposition: form-data; name=" datafile "; filename=" #{File.basename(file)}"rn" post_body << "Content-Type: text/plainrn" post_body << "rn" post_body << File.read(file) post_body << "rn--#{BOUNDARY}--rn" http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Post.new(uri.request_uri) request.body = post_body.join request["Content-Type"] = "multipart/form-data, boundary=#{BOUNDARY}" http.request(request) end def self.ssl_always require 'always_verify_ssl_certificates' AlwaysVerifySSLCertificates.ca_file = "/path/path/path/cacert.pem" http= Net::HTTP.new('https://some.ssl.site', 443) http.use_ssl = true req = Net::HTTP::Get.new('/') response = http.request(req) end def self.ssl_request uri = URI.parse("https://secure.com/") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) response.body response.status response["header-here"] # All headers are lowercase end def ssl_with_pem uri = URI.parse("https://secure.com/") pem = File.read("/path/to/my.pem") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.cert = OpenSSL::X509::Certificate.new(pem) http.key = OpenSSL::PKey::RSA.new(pem) http.verify_mode = OpenSSL::SSL::VERIFY_PEER request = Net::HTTP::Get.new(uri.request_uri) end def rest_methods http = Net::HTTP.new("api.restsite.com") request = Net::HTTP::Post.new("/users") request.set_form_data({ "users[login]" => "quentin" }) response = http.request(request) # Use nokogiri, hpricot, etc to parse response.body. request = Net::HTTP::Get.new("/users/1") response = http.request(request) # As with POST, the data is in response.body. request = Net::HTTP::Put.new("/users/1") request.set_form_data({ "users[login]" => "changed" }) response = http.request(request) request = Net::HTTP::Delete.new("/users/1") response = http.request(request) end def post_test @host = 'localhost' @port = '8099' @path = "/posts" @body ={ "bbrequest" => "BBTest", "reqid" => "44", "data" => { "name" => "test" } }.to_json request = Net::HTTP::Post.new(@path, initheader = { 'Content-Type' => 'application/json' }) request.body = @body response = Net::HTTP.new(@host, @port).start { |http| http.request(request) } puts "Response #{response.code} #{response.message}: #{response.body}" end end
require "test_helper" feature "CanAccessWelcome" do scenario "is displaying welcome" do visit root_path page.must_have_content "Welcome" end end
=begin This plugin allows you to read a news article, also marking it read. =end read = Command.new do name "Read" desc "Lets you read a news article" help <<-eof Using this command you can read news, which is kind of the purpose of having the newsboard here in the first place. eof syntax "+news <postpath>" match(/^(\d+\/)*\d+$/) trigger do |match| post = Util::get_post match[0] next Constants::ERR_NOT_FOUND if post.nil? unless post.read_by? post.was_read_by $CALLER $DIRTY << :news end next NewsMessage.new{|n| n.message = post.display} end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Articles' do describe '#index' do it 'returns all Articles' do create_list(:article, 3) user = create(:user) sign_in(user) get '/api/articles' expect(json_body['articles'].size).to eq(3) expect(json_body['articles'].first.keys).to match_array( [ 'slug', 'title', 'description', 'body', 'tagList', 'createdAt', 'updatedAt', 'favorited', 'favoritesCount', 'author' ] ) expect(json_body['articles'].first['author'].keys).to match_array( ['username', 'bio', 'image', 'following'] ) end end end
class GuiFunctionMembership < ActiveRecord::Base belongs_to :gui_function belongs_to :user_group validates_associated :gui_function validates_associated :user_group end
require 'rails_helper' RSpec.describe "shops/new", type: :view do before(:each) do assign(:shop, Shop.new( :name => "MyString", :prefecture => 1, :address => "MyString", :latitude => 1.5, :longitude => 1.5 )) end it "renders new shop form" do render assert_select "form[action=?][method=?]", shops_path, "post" do assert_select "input#shop_name[name=?]", "shop[name]" assert_select "input#shop_prefecture[name=?]", "shop[prefecture]" assert_select "input#shop_address[name=?]", "shop[address]" assert_select "input#shop_latitude[name=?]", "shop[latitude]" assert_select "input#shop_longitude[name=?]", "shop[longitude]" end end end
module Pact module Message module Consumer class Message attr_accessor :description, :content, :provider_state def initialize attributes = {} @description = attributes[:description] @provider_state = attributes[:provider_state] || attributes[:providerState] @content = attributes[:content] end def to_hash { description: description, provider_state: provider_state, content: content } end def to_json { description: description, providerState: provider_state, content: content } end end end end end
class GlossaryController < ApplicationController def index @page = Page.find_by_absolute_url!("/glossary", select: "id, title, meta_description, teaser, copy") @sorted_terms = sort_terms(GlossaryTerm.all.group_by { |g| g.name.upcase.first }) end #convert a hash into an array sorted alphabetically by the key def sort_terms(hash) sorted = [] hash.each do |key, value| sorted << [key.upcase, value] end sorted.sort{ |x,y| x[0] <=> y[0] } end end
class GroupsController < ApplicationController before_action :new_group, only: :index before_action :load_group, only: [:show, :edit, :destroy, :update, :add_member, :delete_member] before_action :is_owner def index @title = t "groups.list_groups" @search = current_user.admin? ? Group.ransack(params[:q]) : current_user.groups.ransack(params[:q]) @groups = @search.result @groups = @groups.page(params[:page]).per Settings.per_page.admin.group respond_to do |format| format.html format.js end end def show @title = t "groups.information_group" user_ids = @group.users.is_normal_user.search_by(params[:search]).pluck(:id) @users_inside = @group.user_groups.of_user_ids(user_ids).includes(:user) init_variables respond_to do |format| format.html format.js end end def add_member assign_user params[:user_groups][:user_ids], @group redirect_to :back end def delete_member @user_ids = params[:user_ids].strip.split(",").map(&:to_i) unassign_user @user_ids, @group redirect_to :back end private def assign_user user_ids, group assign_user = AssignUserService.new .create user_ids, group, t("user_groups.create_not_successfully") message_notice t("user_groups.create_successfully"), assign_user end def unassign_user user_ids, group unassign_user = AssignUserService.new .destroy user_ids, group, t("user_groups.delete_not_successfully") message_notice t("user_groups.delete_successfully"), unassign_user end def group_params params.require(:group).permit :name, :user_id, :image, :description end def load_group @group = Group.find_by id: params[:id] return if @group flash[:error] = t "not_found_item" redirect_to :back end def new_group @group = Group.new end def message_notice message_success, type return flash[:error] = type[:error] unless type[:success] flash[:success] = message_success end def init_variables @user_group = UserGroup.new @users_outside = User.not_in_group.is_normal_user.includes(:groups) end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/nyaa/version', __FILE__) Gem::Specification.new do |s| s.name = 'nyaa' s.version = Nyaa::VERSION s.homepage = 'https://github.com/mistofvongola/nyaa' s.summary = 'The nyaa gem is a CLI to NyaaTorrents.' s.description = 'Browse and download from NyaaTorrents from the command-line. Supports categories and filters.' s.authors = ['David Palma'] s.email = 'david@davidpalma.me' s.files = `git ls-files`.split("\n") s.executables = s.files.grep(%r{^bin/}).map{ |f| File.basename(f) } s.require_path = ['lib'] s.add_runtime_dependency 'curses', '~> 1.0.1' s.add_runtime_dependency 'nokogiri', '~> 1.6.3' end
class TasksUser < ActiveRecord::Base attr_accessible :sender_id, :task_id, :user_id #belongs_to :sender, calss_name: 'User', foreign_key: :sender_id # belongs_to :user belongs_to :task belongs_to :sender, class_name: 'User', foreign_key: :sender_id validates_presence_of :task_id, :on => :create validates_presence_of :user_id, :on => :create validates_presence_of :sender_id, :on => :create validates_uniqueness_of :task_id, :scope => :user_id end