text
stringlengths
10
2.61M
after_bundler do get_vendor_javascript 'https://raw.github.com/kswedberg/jquery-expander/master/jquery.expander.js', 'jquery.expander' require_javascript 'jquery.expander' # up to you to hook it up in document.ready end __END__ name: Jquery expander description: Add jquery expander script to compress/expand blocks of text website: http://plugins.learningjquery.com/expander/ author: mattolson requires: [jquery] run_after: [jquery] category: javascript
# config-utils.rb # # In the class that you're configuring: # # class MyClass # def init(*args, &block) # config = ConfigStruct.block_to_hash(block) # # process your config ... # end # end # # To configure MyClass: # # MyClass.new.init do |c| # c.some = "config" # c.info = "goes here" # end require 'ostruct' require 'brewed' module Brewed class ConfigStruct < OpenStruct def self.block_to_hash(block=nil) config = self.new if block block.call(config) config.to_hash else {} end end def to_hash @table end end end
# frozen_string_literal: true require_relative 'mixins/command' # split-window (alias: splitw) # [-bdfhIvPZ] # [-c start-directory] [-e environment] [-l size] [-t target-pane] [-F format] # [shell-command] # -e takes the form ‘VARIABLE=value’ and sets an environment # variable for the newly created window; it may be specified # multiple times. module Build module Util class Tmux module SplitWindow include Mixins::Command aka :splitw switch b: :left_or_above switch d: :background switch f: :full_span switch h: :horizontal switch I: :forward_input switch v: :vertical switch P: :print_info switch Z: :zoom flag c: :start_directory # flag e: :environment_variables # TODO flag l: :size flag t: :target_pane flag F: :format end end end end
class RolesController < ApplicationController before_action :set_locale def show @role = Role.find!(request.path) setup_content_item_and_navigation_helpers(@role) render :show, locals: { role: @role } end private def set_locale I18n.locale = params[:locale] || I18n.default_locale end end
namespace :db do desc "populates the database" task :populate, [:amount] => :environment do |t, args| amount = args[:amount].to_i Rake::Task["db:populate_users"].invoke(amount) Rake::Task["db:populate_exercises"].invoke(amount) Rake::Task["db:populate_trainings_sessions"].invoke(amount) Rake::Task["db:populate_events"].invoke(amount) Rake::Task["db:populate_done_trainings_sessions"].invoke(amount) end end
# -*- mode: ruby -*- # vi: set ft=ruby : # Sergey's Vagrant test cluster # Copy it into a separate directory as Vagrantfile to avoid collisions servers=[] (1..3).each do |srv| servers << { :num => srv, :hostname => "devops#{srv}", :ip => "192.168.100.10#{srv}", :box => "travisrowland/centos7", :ram => 512, :cpus => 1 } end # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| servers.each do |machine| config.vm.define machine[:hostname] do |node| node.vm.box = machine[:box] node.vm.hostname = machine[:hostname] node.vm.network "private_network", ip: machine[:ip] node.vm.provider "virtualbox" do |vb| vb.memory = machine[:ram] vb.cpus = machine[:cpus] end node.vm.synced_folder ".", "/vagrant", :mount_options => ["dmode=777","fmode=644"] node.vm.network "forwarded_port", guest: 22, host: "522#{machine[:num]}" node.ssh.insert_key = false node.ssh.private_key_path = ["/Users/evolvah/.ssh/id_rsa-ericsson", "~/.vagrant.d/insecure_private_key"] node.vm.provision "file", source: "/Users/evolvah/.ssh/id_rsa-ericsson.pub", destination: "~/.ssh/authorized_keys" # node.vm.provision :shell, # path: "vagrant-libs/bootstrap.sh" end end end
class Destination < ApplicationRecord validates_presence_of :city, :state, :latitude, :longitude, :population has_many :routes, dependent: :destroy has_many :trips, through: :routes def self.search(term) dest = Destination.arel_table where(dest[:city].matches("%#{term}%").or(dest[:state].matches("%#{term}%"))) end def self.sort_city order("city ASC") end end
class AddPetsToApplicationPets < ActiveRecord::Migration[5.2] def change add_reference :application_pets, :pet, foreign_key: true end end
class ArticlesController < ApplicationController before_filter :authenticate_user! def academy_board if Tag.any? @academy_board = true @tags_one = Tag.order('id asc').limit(3) @tags_two = Tag.order('id asc').offset(3).limit(2) else redirect_to root_path end end def index user_tags = current_user.usertags if user_tags.any? @academy_board = true articles = Article.tagged_with(user_tags.pluck(:tag_id)) if params[:sort].present? articles = articles.order("#{params[:sort]}") else articles = articles.order('title asc') end @articles = articles.page params[:page] else redirect_to academy_board_path, notice: 'You have to select at least one category...' end end def show redirect_to academy_board_path end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) people = [["Carly", "Fiorina", "female", 1954], ["Donald", "Trump", "male", 1946], ["Ben", "Carson", "male", 1951], ["Hillary", "Clinton", "female", 1947]] users = User.create! people.map{|p| {username: p[1], password_digest: p[1].downcase}} Profile.create! people.zip(users).map{|p, u| {first_name: p[0], last_name: p[1], gender: p[2], birth_year: p[3], user: u}} lists = TodoList.create! people.zip(users).map{|p, u| {list_name: "#{p[0]}'s TODO", list_due_date: Date.today.next_year, user: u}} TodoItem.create! lists.product((1..5).to_a).map{|l, i| {due_date: Date.today.next_year, title: "Item #{i}", description: "Description #{i}", completed: false, todo_list: l}}
module Haenawa module Commands class SendKeys < Command VALID_KEYS = [ '${KEY_ENTER}' ] def validate if target.blank? @step.errors.add(:target, :missing) elsif !VALID_STRATEGIES.include?(strategy) || locator.blank? @step.errors.add(:target, :invalid) end if value.blank? @step.errors.add(:value, :missing) elsif !VALID_KEYS.include?(key) @step.errors.add(:value, :invalid) end end def key case value when /\${KEY_([A-Z]+).*}/ ':' + $1.downcase else value end end def render ensure_capture do "#{find_target}.send_keys(#{key})" end rescue Haenawa::Exceptions::Unsupported::TargetType render_unsupported_target end end end end
require 'test_helper' class Finerworks2Test < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Finerworks2::VERSION end end
FactoryBot.define do factory :address do zipcode { "03004-001" } public_place { "Rua do Gasometro" } number { "100" } complement { "Complemento" } neighborhood { "Brás" } city { "São Paulo" } state { "SP" } ibge_code { "12345" } end end
class Vehicles attr_reader :make, :model, :wheels def initialize(make, model, wheels) @make = make @model = model @wheels = wheels end def to_s "#{make} #{model}" end end class Car < Vehicles def initialize(make, model) super(make, model, 4) end end class Motorcycle < Vehicles def initialize(make, model) super(make, model, 2) end end class Truck < Vehicles attr_reader :payload def initialize(make, model, payload) super(make, model, 6) @payload = payload end end p Car.new('2012', 'Mazda') p Motorcycle.new('2000', 'Thosiba') p Truck.new('100', 'llk', 'payload1')
class Restaurante def qualifica(nota, msg="Obrigado") puts "A nota do restaurante foi #{nota}. #{msg}" end end
class Telefone < ApplicationRecord belongs_to :pessoa validates :ddd, :numero, :tipo, presence: true validates_with TelefoneValidator def tem_preferencial? return (Telefone.where(pessoa_id: self.pessoa_id, preferencial: true).blank?) ? false : true end end
require "rails_helper" RSpec.shared_context "with finished deployment" do before { create(:deployment, :finished, project: project) } end RSpec.shared_examples "with failed deployment" do before { create(:deployment, :failed, project: project) } end RSpec.shared_examples "successful publish" do it { is_expected.to be true } it "updates released_at" do expect { subject }.to change { project.reload.released_at } end it "calls publisher" do expect(publisher).to receive(:publish) subject end end RSpec.shared_examples "skipped publish" do it { is_expected.to be false } it "doesn't update released_at" do expect { subject }.not_to change { project.reload.released_at } end it "doesn't call publisher" do expect(publisher).not_to receive(:publish) subject end end RSpec.shared_examples "successful unpublish" do let(:cleaner) { class_double(Cleaner).as_stubbed_const } before { allow(cleaner).to receive(:clean).with(project) } it "calls cleaner" do expect(cleaner).to receive(:clean).with(project) subject end it "updates project to hidden" do expect { subject }.to change { project.reload.hidden? } end end RSpec.shared_examples "skipped unpublish" do let(:cleaner) { class_double(Cleaner).as_stubbed_const } before { allow(cleaner).to receive(:clean).with(project) } it "doesn't call cleaner" do expect(cleaner).not_to receive(:clean) subject end it "doesn't update project to hidden" do expect { subject }.not_to change { project.reload.hidden? } end end RSpec.describe Project, type: :model do describe "#valid?" do let(:project) { build(:project) } subject { project.valid? } it { is_expected.to be true } context "when user is nil" do let(:project) { build(:project, user: nil) } it { is_expected.to be false } end context "when title is blank" do let(:project) { build(:project, title: " ") } it { is_expected.to be false } end context "when name is blank" do let(:project) { build(:project, name: " ") } it { is_expected.to be false } end context "when name is taken" do let(:project) { build(:project, name: "foo") } before { create(:project, name: "foo") } it { is_expected.to be false } end context "when name is 63 characters long" do let(:project) { build(:project, name: "a" * 63) } it { is_expected.to be true } end context "when name is longer than 63 characters" do let(:project) { build(:project, name: "a" * 64) } it { is_expected.to be false } end context "when name contains uppercase letters" do let(:project) { build(:project, name: "fooBarBaz") } it { is_expected.to be false } end context "when name contains digits" do let(:project) { build(:project, name: "f00b4rb4z") } it { is_expected.to be true } end context "when name contains dashes" do let(:project) { build(:project, name: "foo-bar-baz") } it { is_expected.to be true } end context "when name contains underscores" do let(:project) { build(:project, name: "foo_bar_baz") } it { is_expected.to be false } end context "when name contains whitespace characters" do let(:project) { build(:project, name: "foo bar baz") } it { is_expected.to be false } end context "when name starts with a letter" do let(:project) { build(:project, name: "foo") } it { is_expected.to be true } end context "when name starts with a number" do let(:project) { build(:project, name: "1337") } it { is_expected.to be true } end context "when name starts with a dash" do let(:project) { build(:project, name: "-foo") } it { is_expected.to be false } end context "when name ends with a dash" do let(:project) { build(:project, name: "foo-") } it { is_expected.to be false } end end describe "#url" do let(:project) { build(:project, name: "foo") } subject { project.url } it { is_expected.to eq "http://www.example.com/foo/index.html" } end describe "#hidden?" do subject { project.hidden? } context "when released? is true" do let(:project) { create(:project, :released) } it { is_expected.to be false } end context "when released? is false" do let(:project) { create(:project) } it { is_expected.to be true } end end describe "#released?" do subject { project.released? } context "when released_at is nil" do let(:project) { create(:project, released_at: nil) } it { is_expected.to be false } end context "when released_at is not nil" do let(:project) { create(:project, released_at: Time.current) } it { is_expected.to be true } end end describe "#deployed?" do let(:project) { create(:project) } subject { project.deployed? } context "when there are no deployments" do it { is_expected.to be false } end context "when there is one deployment" do context "when deployment has finished" do include_context "with finished deployment" it { is_expected.to be true } end context "when deployment has failed" do include_context "with failed deployment" it { is_expected.to be false } end end context "when there are two deployments" do context "when both deployments have finished" do include_context "with finished deployment" include_context "with finished deployment" it { is_expected.to be true } end context "when both deployments have failed" do include_context "with failed deployment" include_context "with failed deployment" it { is_expected.to be false } end context "when first deployment has finished and second deployment failed" do include_context "with finished deployment" include_context "with failed deployment" it { is_expected.to be true } end context "when first deployment has failed and second deployment finished" do include_context "with failed deployment" include_context "with finished deployment" it { is_expected.to be true } end end end describe "#published?" do subject { project.published? } context "when released? is true and deployed? is true" do let(:project) { create(:project, :released, :deployed) } it { is_expected.to be true } end context "when released? is true" do let(:project) { create(:project, :released) } it { is_expected.to be false } end context "when deployed? is true" do let(:project) { create(:project, :deployed) } it { is_expected.to be false } end end describe "#deployment_failed?" do let(:project) { create(:project) } subject { project.deployment_failed? } context "when there are no deployments" do it { is_expected.to be false } end context "when there is one deployment" do context "when deployment has finished" do include_context "with finished deployment" it { is_expected.to be false } end context "when deployment has failed" do include_context "with failed deployment" it { is_expected.to be true } end end context "when there are two deployments" do context "when both deployments have finished" do include_context "with finished deployment" include_context "with finished deployment" it { is_expected.to be false } end context "when both deployments have failed" do include_context "with failed deployment" include_context "with failed deployment" it { is_expected.to be true } end context "when first deployment has finished and second deployment failed" do include_context "with finished deployment" include_context "with failed deployment" it { is_expected.to be true } end context "when first deployment has failed and second deployment finished" do include_context "with failed deployment" include_context "with finished deployment" it { is_expected.to be false } end end end describe "#deployment_fail_message" do subject { project.deployment_fail_message } context "when deployment_failed? is true" do let(:project) { create(:project, :deployment_failed) } it { is_expected.to eq "fail" } end context "when deployment_failed? is false" do let(:project) { create(:project) } it { is_expected.to be_nil } end end describe "#current_deployment" do let(:project) { create(:project) } let!(:first_project) { create(:deployment, project: project, created_at: 2.hours.ago) } let!(:second_project) { create(:deployment, project: project, created_at: 1.hour.ago) } let!(:third_project) { create(:deployment, project: project, created_at: 3.hours.ago) } subject { project.current_deployment } it { is_expected.to eq second_project } end describe "#status" do subject { project.status } context "when released? is true" do context "when deployed? is true" do context "when discarded? is true" do let(:project) { create(:project, :released, :deployed, :discarded) } it { is_expected.to eq "Deleting" } end context "when discarded? is false" do let(:project) { create(:project, :released, :deployed) } it { is_expected.to eq "Published" } end end context "when deployed? is false" do context "when discarded? is true" do context "when deployment_failed? is true" do let(:project) { create(:project, :released, :discarded, :deployment_failed) } it { is_expected.to eq "Deleting" } end context "when deployment_failed? is false" do let(:project) { create(:project, :released, :discarded) } it { is_expected.to eq "Deleting" } end end context "when discarded? is false" do context "when deployment_failed? is true" do let(:project) { create(:project, :released, :deployment_failed) } it { is_expected.to eq "Error" } end context "when deployment_failed? is false" do let(:project) { create(:project, :released) } it { is_expected.to eq "Publishing" } end end end end context "when hidden? is true" do context "when discarded? is true" do let(:project) { create(:project, :discarded) } it { is_expected.to eq "Deleting" } end context "when discarded? is false" do let(:project) { create(:project) } it { is_expected.to eq "Unpublished" } end end end describe "#publish" do let(:publisher) { class_double("Publisher").as_stubbed_const } before { allow(publisher).to receive(:publish).and_return("foo") } subject { project.publish } context "when released_at? is false and discarded? is false" do let(:project) { create(:project) } include_examples "successful publish" end context "when discarded? is true" do let(:project) { create(:project, :discarded) } include_examples "skipped publish" end context "when released_at? is true" do context "when deployment_failed? is true" do let(:project) { create(:project, :released, :deployment_failed) } include_examples "successful publish" end context "when deployment_failed? is false" do let(:project) { create(:project, :released) } include_examples "skipped publish" end end end describe "#unpublish" do let(:project) { create(:project, :published) } subject { project.unpublish } include_examples "successful unpublish" end describe "#confirm_cleanup" do subject { project.confirm_cleanup } context "when discarded? is true" do let!(:project) { create(:project, :discarded) } it { is_expected.to be_a(Project) } it "deletes project" do expect { subject }.to change { Project.count }.by(-1) end end context "when discarded? is false" do let!(:project) { create(:project) } it { is_expected.to be false } it "doesn't delete project" do expect { subject }.not_to change { Project.count } end end end context "when project is updated" do let(:project) { create(:project, title: "foo", name: "foo") } subject { project.update(title: "bar", name: "bar") } it "prevents name updates" do expect { subject }.not_to change { project.reload.name } end end context "when project is discarded" do subject { project.discard } context "when published? is true" do let(:project) { create(:project, :published) } include_examples "successful unpublish" end context "when published? is false" do let(:project) { create(:project) } context "when released? is true" do skip "hides project" end context "when released? is false" do include_examples "skipped unpublish" context "when deployed? is true" do skip "removes deployment" end end end end context "when project is destroyed" do let(:project) { create(:project) } subject { project.destroy } it "destroys any deployments" do create(:deployment, project: project) expect { subject }.to change { Deployment.count }.by(-1) end end end
module ::Forem class Engine < Rails::Engine isolate_namespace Forem class << self attr_accessor :root def root @root ||= Pathname.new(File.expand_path('../../', __FILE__)) end end initializer 'engine.helper' do |app| ActionView::Base.send :include, Forem::ApplicationHelper end end end require 'simple_form'
class Editar < SitePrism::Page element :search_btn, '#searchbutton' element :search_field, '#query_string' element :task, '#pagecontent > table > tbody:nth-child(3) > tr > td:nth-child(2) > a' def SearchTask search_btn.click search_field.set(task) task.click end end
class ShowOffUtils def self.create dirname = ARGV[1] return help('create') if !dirname Dir.mkdir(dirname) if !File.exists?(dirname) Dir.chdir(dirname) do # create section Dir.mkdir('one') # create markdown file File.open('one/slide.md', 'w+') do |f| f.puts "!SLIDE" f.puts "# My Presentation #" f.puts f.puts "!SLIDE bullets incremental" f.puts "# Bullet Points #" f.puts f.puts "* first point" f.puts "* second point" f.puts "* third point" end # create showoff.json File.open('showoff.json', 'w+') do |f| f.puts '[ {"section":"one"} ]' end # print help puts "done. run 'showoff serve' in #{dirname}/ dir to see slideshow""" end end def self.heroku name = ARGV[1] return help('heroku') if !name if !File.exists?('showoff.json') puts "fail. not a showoff directory" return false end # create .gems file File.open('.gems', 'w+') do |f| f.puts "bluecloth" f.puts "nokogiri" f.puts "showoff" end if !File.exists?('.gems') # create config.ru file File.open('config.ru', 'w+') do |f| f.puts 'require "showoff"' f.puts 'run ShowOff.new' end if !File.exists?('config.ru') puts "herokuized. run something like this to launch your heroku presentation: heroku create #{name} git add .gems config.ru git commit -m 'herokuized' git push heroku master " end def self.help(verb = nil) verb = ARGV[1] if !verb case verb when 'heroku' puts <<-HELP usage: showoff heroku (heroku-name) creates the .gems file and config.ru file needed to push a showoff pres to heroku. it will then run 'heroku create' for you to register the new project on heroku and add the remote for you. then all you need to do is commit the new created files and run 'git push heroku' to deploy. HELP when 'create' puts <<-HELP usage: showoff create (directory) this command helps start a new showoff presentation by setting up the proper directory structure for you. it takes the directory name you would like showoff to create for you. HELP else puts <<-HELP usage: showoff (command) commands: serve serves a showoff presentation from the current directory create generates a new showoff presentation layout heroku sets up your showoff presentation to push to heroku HELP end end end
atom_feed do |feed| feed.title @title latest = @videos.sort_by(&:created_at).last feed.updated(latest && latest.created_at) @videos.each do |video| feed.entry(video) do |entry| entry.url video_path(video) entry.title "Video saved " + video.created_at.strftime("%A, %B %Y") entry.summary type: 'xhtml' do |xhtml| xhtml.iframe src: video.embed_url, width: "500", height: "401" end entry.author do |author| author.name video.user.email end end end end
class Review < ActiveRecord::Base belongs_to :user belongs_to :concert #custom_writer def concert_attributes=(concert_attributes) self.create_concert(concert_attributes) if concert_id.nil? end end
module FormObject class DateTimeType class << self def process(params, name) value = params[name] || params[name.to_s] return value if value && value.class == DateTime return value.to_datetime if value && value.respond_to?(:to_datetime) year = params["#{name}(1i)"] month = params["#{name}(2i)"] day = params["#{name}(3i)"] hour = params["#{name}(4i)"] minute = params["#{name}(5i)"] second = params["#{name}(6i)"] if [year, month, day, hour, minute, second].any?(&:present?) time_zone_offset = Time.zone.formatted_offset rescue '+00:00' DateTime.new(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, second.to_i).change(offset: time_zone_offset) rescue nil end end end end self.field_types[:datetime] = DateTimeType end
# frozen_string_literal: true class StudentComponents::StudentTable < ViewComponent::Base delegate :excluding_deleted?, :show_deleted_url, :student_group_name, :policy, to: :helpers def initialize students = StudentTableRow.includes(:tags, { group: { chapter: :organization } }) @pagy, @students = yield(students) end # rubocop:disable Metrics/MethodLength def columns [ { column_name: '#' }, { order_key: :full_mlid, column_name: t(:mlid), numeric: true }, { order_key: :last_name, column_name: t(:last_name) }, { order_key: :first_name, column_name: t(:first_name) }, { order_key: :gender, column_name: t(:gender) }, { order_key: :dob, column_name: t(:date_of_birth), numeric: true }, { column_name: t(:tags) }, { order_key: :group_name, column_name: t(:group) }, { column_name: t(:actions) } ] end # rubocop:enable Metrics/MethodLength end
class AddMiniDraftToRounds < ActiveRecord::Migration[5.0] def change reversible do |dir| dir.up do add_column :rounds, :mini_draft, :boolean Round.where('deadline_time > ?', Round::SUMMER_MINI_DRAFT_DEADLINE).first.update(mini_draft: true) Round.where('deadline_time > ?', Round::WINTER_MINI_DRAFT_DEALINE).first.update(mini_draft: true) end dir.down do remove_column :rounds, :mini_draft, :boolean end end end end
# == Schema Information # # Table name: users # # id :bigint not null, primary key # first_name :string not null # last_name :string not null # email :string not null # breed :string # about_me :text # password_digest :string not null # session_token :string not null # created_at :datetime not null # updated_at :datetime not null # country :string # region :string # class User < ApplicationRecord validates_presence_of :first_name, :last_name, :email validates_uniqueness_of :email validate :password_presence validates :password, length: { minimum: 6 }, allow_nil: true validate :profile_photo_is_image after_initialize :ensure_session_token attr_reader :password has_one_attached :profile_photo has_many :posts, foreign_key: :author_id, class_name: :Post has_many :reactions, foreign_key: :liker_id, class_name: :Reaction has_many :liked_posts, through: :reactions, source: :post has_many :comments, foreign_key: :author_id, class_name: :Comment def connections Connection.where("(user_id1 = ? OR user_id2 = ?) AND status = 'connected'", self.id, self.id) end def connected_users users = connections.map do |connection| if connection.user_id1 == self.id connection.user_id2 else connection.user_id1 end end User.where("id IN (?)", users) end def connection_requests Connection.where("(user_id1 = ? AND status = 'pending_user1') OR (user_id2 = ? AND status = 'pending_user2')", self.id, self.id) end def users_requesting_connection users = connection_requests.map do |request| if request.user_id1 == self.id request.user_id2 else request.user_id1 end end User.where('id IN (?)', users) end def requested_connections Connection.where("(user_id1 = ? AND status = 'pending_user2') OR (user_id2 = ? AND status = 'pending_user1')", self.id, self.id) end def pending_users users = requested_connections.map do |request| if request.user_id1 == self.id request.user_id2 else request.user_id1 end end User.where('id IN (?)', users) end def pups_you_may_know pups = []; connects = connected_users; if connects.empty? pups = User.where("id <> ?", self.id).limit(10); end connects.each do |user| user.connected_users.each do |second_connection| unless second_connection == self || connects.include?(second_connection) || pups.include?(second_connection) pups << second_connection end end end if pups.length < 5 ids = connects.pluck(:id).concat(pups.pluck(:id)) << self.id length = 5 - pups.length pups << User.where("id NOT IN (?)", ids).limit(length) end pups end def self.generate_session_token SecureRandom::urlsafe_base64 end def ensure_session_token self.session_token ||= User.generate_session_token end def reset_session_token! self.session_token = User.generate_session_token self.save! self.session_token end def self.find_by_credentials(email, password) user = User.find_by(email: email) if user && user.is_password?(password) return user elsif user.nil? return {email: 'Please enter a valid username'} elsif password.nil? || password.empty? return {password: 'Please enter a password'} elsif password.length < 6 return {password: 'The password you provided must have at least 6 characters.'} else return {password: "That's not the right password. Try again"} end end def is_password?(password) password_object = BCrypt::Password.new(self.password_digest) password_object.is_password?(password) end def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end private def password_presence errors.add(:password, "can't be blank") if self.password_digest.nil? end def profile_photo_is_image if profile_photo.attached? && !['image/png', 'image/jpg', 'image/jpeg'].include?(profile_photo.blob.content_type) profile_photo.purge errors.add(:profile_photo, "must be an image (png, jpg, jpeg)") end end end
class CreateTravelPlans < ActiveRecord::Migration[5.0] def change create_table :travel_plans do |t| t.references :user, index: true, foreign_key: { on_delete: :cascade }, null: false t.integer :type, index: true, null: false, default: 0 t.daterange :departure_date_range, null: false t.integer :no_of_passengers, null: false, default: 1 t.timestamps end end end
describe EasyRakeTaskRepeatingEntities do it 'create issue to be repeated with righ params' do author = FactoryGirl.create(:user, :lastname => 'Author') assigned_to = FactoryGirl.create(:user, :lastname => 'Assignee') issue = FactoryGirl.create(:issue, :reccuring, :author => author, :assigned_to => assigned_to) rake_task = EasyRakeTaskRepeatingEntities.new(:active => true, :settings => {}, :period => :daily, :interval => 1, :next_run_at => Time.now) $stdout.stubs(:puts) expect{ rake_task.execute }.to change(Issue,:count).by(1) issue.reload issue.relations_from.count.should == 1 issue_to = issue.relations_from.first.issue_to issue_to.author.should == author issue_to.assigned_to.should == assigned_to end it 'set right repeat date, when created' do issue = FactoryGirl.create(:issue, :reccuring_monthly) repeat_day = issue.easy_repeat_settings['monthly_day'].to_i issue.easy_next_start.should == (Date.today + repeat_day.days - Date.today.mday.days) end end
=begin rdoc Пользователи =end class User < ActiveRecord::Base attr_accessible :login, :email, :password, :password_confirmation, :city_name, :active, :role_ids acts_as_authentic do |c| c.login_field = 'email' end # Associations has_and_belongs_to_many :roles has_many :magazines has_many :products has_many :tickets has_many :replies def categories categories = [] self.products.each {|x| categories << x.category unless categories.include?(x.category);} categories end # Validations validates_presence_of :email, :city_name # callback after_create :add_default_role # named_scope default_scope :order => "id" named_scope :active, :conditions => {:active => true} named_scope :inactive, :conditions => {:active => false} def add_default_role add_role(:user) end def signup!(params) self.login = params[:user][:login] self.email = params[:user][:email] self.password = params[:user][:password] self.password_confirmation = params[:user][:password_confirmation] save_without_session_maintenance end def activate! self.active = true save end # deliver def deliver_activation_instructions! reset_perishable_token! Notifier.deliver_activation_instructions(self) end def deliver_activation_confirmation! reset_perishable_token! Notifier.deliver_activation_confirmation(self) end def deliver_password_reset_instructions! reset_perishable_token! Notifier.deliver_password_reset_instructions(self) end # roles def has_role?(role) self.roles.count(:conditions => ["name = ?", role.to_s]) > 0 end # user.add_role("admin") def add_role(role) return if self.has_role?(role) self.roles << Role.find_by_name(role.to_s) end def remove_role(role) return false unless self.has_role?(role) role = Role.find_by_name(role) self.roles.delete(role) end def admin? @_roles ||= roles self.has_role?("admin") end # permissions def role_symbols (roles || []).map{ |x| x.name.underscore.to_sym } end def self.not_admin self.all.select {|x| !x.admin? } end def self.admins self.all.select {|x| x.admin? } end end
# -*- coding: utf-8 -*- module TextToNoise class NoiseMapping include Logging attr_accessor :targets, :matcher_conditions, :filter_conditions def initialize( expression_or_map, &block ) debug "Parsing expression: #{expression_or_map.inspect}" @matcher_conditions = [] @filter_conditions = [] @regex = nil case expression_or_map when Regexp @regex = expression_or_map when Hash expression_or_map.each do |k,v| case k when Regexp @regex = k self.to v else self.send k.to_sym, v end end else raise ArgumentError, "Unrecognized Mapping configuration: #{expression_or_map.inspect}" end raise ArgumentError, "Bad configuration line. Missing match expression in \"#{expression_or_map.inspect}\"" if @regex.nil? matcher_conditions << block if block_given? filter_conditions << Conditions::ThrottledMatchCondition.new end def ===( other ) match_data = @regex.match( other ) !match_data.nil? && play?( match_data ) end def to( sound_or_sounds ) if sound_or_sounds.is_a? Array sounds = sound_or_sounds else sounds = [sound_or_sounds] end sounds.each do |sound| s = sound s += ".wav" unless sound =~ /.wav$/ self.targets << Proc.new { info "#{self.class.name} : #{@regex.inspect} -> #{sound}" TextToNoise.player.play s } end self end def every( iteration_count ) @matcher_conditions << Conditions::IterationMappingCondition.new( iteration_count ) self end def when( &clause ) @matcher_conditions << clause self end def call() debug "Calling '#{@regex.inspect}' target…" target.call end def targets() @targets ||= []; end def target() raise "No Sound mapped for rule: '#{@regex.inspect}'" if targets.empty? @i = -1 unless @i @i = (@i + 1) % targets.size self.targets[@i] end private def play?( match_data ) return false unless @filter_conditions.all? { |c| c.call match_data } return true if @matcher_conditions.empty? @matcher_conditions.any? { |c| c.call match_data } end end end
json.metadata do json.users_count @users_count json.books_count @books_count json.requests_count @requests_count json.conversations_count @conversations_count end
class Api::GamesController < Api::ApplicationController before_action :authenticate_user! def show game = Game.find(current_user.game&.id) render_json game, include: {seats: {user: true, river: :tiles, hand: :tiles}} end def create room = current_user.room head :unprocessable_entity unless room.game_startable?(current_user) game = Game.new(room: room) room.transaction do game.save! game.scenes.create!(mahjong: Mahjong.create(room.users)) end room.users.each do |user| notify(user: user, event: 'room:update', resource: room) end head :ok end end
module Refinery module Fg class Teacher < Refinery::Core::BaseModel attr_accessible :name, :desc, :content, :works, :avatar_id, :title, :position acts_as_indexed :fields => [:name, :title, :works, :desc, :content] validates :name, :presence => true, :uniqueness => true belongs_to :avatar, :class_name => '::Refinery::Image' end end end
class Auction::ImportWorker include Sidekiq::Worker def initialize @wow_client = WowClient.new(logger) end def perform(auction_hash) logger.info "Performing import job auction_hash = #{auction_hash.inspect}" auction_hash.deep_symbolize_keys! item = @wow_client.create_or_update_item(auction_hash[:item]) character = @wow_client.create_or_update_character(auction_hash[:owner], auction_hash[:ownerRealm]) auction = Auction.find_by_id(auction_hash[:auc]) if auction auction.update_attributes(bid: auction_hash[:bid], quantity: auction_hash[:quantity], buyout: auction_hash[:buyout], time_left: auction_hash[:timeLeft]) else if (character && item) auction = character.auctions.create!(item: item, realm: character.realm, bid: auction_hash[:bid], quantity: auction_hash[:quantity], buyout: auction_hash[:buyout], time_left: auction_hash[:timeLeft]) end end end end
class Incident < ApplicationRecord has_many :posts has_many :users has_many_attached :images acts_as_taggable # Alias for acts_as_taggable_on :tags end
module Spree module Core # THIS FILE SHOULD BE OVER-RIDDEN IN YOUR SITE EXTENSION! # the exact code probably won't be useful, though you're welcome to modify and reuse # the current contents are mainly for testing and documentation # To override this file... # 1) Make a copy of it in your sites local /lib/spree folder # 2) Add it to the config load path, or require it in an initializer, e.g... # # # config/initializers/spree.rb # require 'spree/core/product_filters' # # set up some basic filters for use with products # # Each filter has two parts # * a parametrized named scope which expects a list of labels # * an object which describes/defines the filter # # The filter description has three components # * a name, for displaying on pages # * a named scope which will 'execute' the filter # * a mapping of presentation labels to the relevant condition (in the context of the named scope) # * an optional list of labels and values (for use with object selection - see taxons examples below) # # The named scopes here have a suffix '_any', following Ransack's convention for a # scope which returns results which match any of the inputs. This is purely a convention, # but might be a useful reminder. # # When creating a form, the name of the checkbox group for a filter F should be # the name of F's scope with [] appended, eg "price_range_any[]", and for # each label you should have a checkbox with the label as its value. On submission, # Rails will send the action a hash containing (among other things) an array named # after the scope whose values are the active labels. # # Ransack will then convert this array to a call to the named scope with the array # contents, and the named scope will build a query with the disjunction of the conditions # relating to the labels, all relative to the scope's context. # # The details of how/when filters are used is a detail for specific models (eg products # or taxons), eg see the taxon model/controller. # See specific filters below for concrete examples. module ProductFilters def ProductFilters.option_with_values(option_scope, option, values) # get values IDs for Option with name {@option} and value-names in {@values} for use in SQL below option_values = Spree::OptionValue.where(:presentation => [values].flatten).joins(:option_type).where(OptionType.table_name => {:name => option}).pluck("#{OptionValue.table_name}.id") return option_scope if option_values.empty? option_scope = option_scope.where("#{Product.table_name}.id in (select product_id from #{Variant.table_name} v left join spree_option_values_variants ov on ov.variant_id = v.id where ov.option_value_id in (?))", option_values) option_scope end # option scope Spree::Product.scope :option_any, lambda { |*opts| option_scope = Spree::Product.includes(:variants_including_master) opts.map { |opt| option_scope = option_with_values(option_scope, *opt) } option_scope } # color options def ProductFilters.child_colors_any_by_taxon(taxon: "all") if taxon == "all" child_colors = Spree::OptionValue.where(:option_type_id => Spree::OptionType.find_by_name("child_color")).order("position").compact.uniq else # parent_opt_id = Spree::OptionType.find_by(name: "parent_color").id # parent_colors = taxon.products.map(&:variants).flatten.map(&:option_values).flatten.select { |ov| ov.option_type_id == parent_opt_id }.uniq child_opt_id = Spree::OptionType.find_by(name: "child_color").id child_colors = taxon.products.map(&:variants).flatten.map(&:option_values).flatten.select { |ov| ov.option_type_id == child_opt_id }.compact.uniq end labels = child_colors.map { |label| [label.presentation.titleize, label.name] } { :name => "child-color", :scope => :option_any, :conds => nil, :option => 'child_color', :class => "child-color", :labels => labels } # color_filters = {} # parent_colors.each do |pc| # color_filters[pc.name] = [] # child_colors.each do |cc| # if COLOR_PAIRS[pc.name].include? cc.name # color_filters[pc.name] << cc.name # end # end # end # return color_filters end def ProductFilters.parent_color_any(taxon: "all") if taxon == "all" parent_colors = Spree::OptionValue.where(:option_type_id => Spree::OptionType.find_by_name("parent_color")).order("position").compact.uniq else opt = Spree::OptionType.find_by(name: "parent_color").id parent_colors = taxon.products.map(&:variants).flatten.map(&:option_values).flatten.select { |ov| ov.option_type_id == opt }.uniq end labels = parent_colors.map { |label| [label.presentation, label.name] } { :name => "parent-color", :scope => :option_any, :conds => nil, :option => 'parent_color', :class => "parent-color", :labels => labels } end def ProductFilters.child_color_any( parent_color ) child_colors = Spree::OptionValue.where(:option_type_id => Spree::OptionType.find_by_name("child_color")).where(name: COLOR_PAIRS[parent_color]).order("position").compact.uniq labels = child_colors.map { |label| [label.presentation, label.name] } { :name => "child-color", :scope => :option_any, :conds => nil, :option => 'child_color', :class => "child-color", :labels => labels } end def ProductFilters.designer_any(taxon: "all") designer_property = Spree::Property.find_by(name: 'designer') if taxon == "all" designers = designer_property ? Spree::ProductProperty.where(property_id: designer_property.id).pluck(:value).uniq.map(&:to_s) : [] else designers = taxon.products.map { |p| p.property("designer") }.flatten.compact.uniq end labels = designers.reject(&:empty?).map { |label| [label.titleize, label.downcase] }.sort michael_kors = [ "Michael Kors","michael kors"] if labels.include? michael_kors michael_kors_index = labels.index(michael_kors) labels = labels.insert(0, labels.delete_at(michael_kors_index)) end { :name => "designer", :scope => :option_any, :conds => nil, :option => 'designer', :class => "designer", :labels => labels } end def ProductFilters.lapel_any lapel_property = Spree::Property.find_by(name: 'lapel') lapels = lapel_property ? Spree::ProductProperty.where(property_id: lapel_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = lapels.reject(&:empty?).map { |label| [label.titleize, label.downcase] }.sort { :name => "lapel", :scope => :option_any, :conds => nil, :option => 'lapel', :class => "lapel", :labels => labels } end def ProductFilters.fit_any fit_property = Spree::Property.find_by(name: 'fit') fits = fit_property ? Spree::ProductProperty.where(property_id: fit_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = fits.reject(&:empty?).map { |label| [label.titleize, label.downcase] } { :name => "fit", :scope => :option_any, :conds => nil, :option => 'fit', :class => "fit", :labels => labels } end def ProductFilters.buttons_any buttons_property = Spree::Property.find_by(name: 'buttons') buttonss = buttons_property ? Spree::ProductProperty.where(property_id: buttons_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = buttonss.reject(&:empty?).map { |label| [label.titleize, label.downcase] }.sort { :name => "buttons", :scope => :option_any, :conds => nil, :option => 'buttons', :class => "buttons", :labels => labels } end def ProductFilters.coat_style_any coat_style_property = Spree::Property.find_by(name: 'coat_style') coat_styles = coat_style_property ? Spree::ProductProperty.where(property_id: coat_style_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = coat_styles.reject(&:empty?).map { |label| [label.titleize, label.downcase] }.sort { :name => "coat-style", :scope => :option_any, :conds => nil, :option => 'coat_style', :class => "coat-style", :labels => labels } end def ProductFilters.pant_style_any pant_style_property = Spree::Property.find_by(name: 'pant_style') pant_styles = pant_style_property ? Spree::ProductProperty.where(property_id: pant_style_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = pant_styles.reject(&:empty?).map { |label| [label.titleize, label.downcase] }.sort { :name => "pant-style", :scope => :option_any, :conds => nil, :option => 'pant_style', :class => "pant-style", :labels => labels } end def ProductFilters.shirt_style_any shirt_style_property = Spree::Property.find_by(name: 'shirt_style') shirt_styles = shirt_style_property ? Spree::ProductProperty.where(property_id: shirt_style_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = shirt_styles.reject(&:empty?).map { |label| [label.titleize, label.downcase] }.uniq.sort { :name => "shirt-style", :scope => :option_any, :conds => nil, :option => 'shirt_style', :class => "shirt-style", :labels => labels } end def ProductFilters.tie_style_any tie_style_property = Spree::Property.find_by(name: 'tie_style') tie_styles = tie_style_property ? Spree::ProductProperty.where(property_id: tie_style_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = tie_styles.reject(&:empty?).map { |label| [label.titleize, label.downcase] }.uniq.sort { :name => "tie-style", :scope => :option_any, :conds => nil, :option => 'tie_style', :class => "tie-style", :labels => labels } end def ProductFilters.vest_style_any vest_style_property = Spree::Property.find_by(name: 'vest_style') vest_styles = vest_style_property ? Spree::ProductProperty.where(property_id: vest_style_property.id).pluck(:value).uniq.map(&:to_s) : [] labels = vest_styles.reject(&:empty?).map { |label| [label.titleize, label.downcase] } { :name => "vest-style", :scope => :option_any, :conds => nil, :option => 'vest_style', :class => "vest-style", :labels => labels } end # def ProductFilters.selective_brand_filter(taxon = nil) # taxon ||= Spree::Taxonomy.first.root # brand_property = Spree::Property.find_by(name: 'Brand') # scope = Spree::ProductProperty.where(property: brand_property). # joins(product: :taxons). # where("#{Spree::Taxon.table_name}.id" => [taxon] + taxon.descendants) # brands = scope.pluck(:value).uniq # { # name: 'Designer', # scope: :selective_brand_any, # labels: brands.sort.map { |k| [k, k] } # } # end # Spree::Product.add_search_scope :parent_color_any do |*opts| # conds = opts.map {|o| ProductFilters.color_filter[:conds][o]}.reject { |c| c.nil? } # scope = conds.shift # conds.each do |new_scope| # scope = scope.or(new_scope) # end # # Spree::Product.with_property('Parent Color').where(scope) # Spree::Variant.all.select { |v| v.option_values.where("option_values.name = ?", "Parent Color" ) }.collect { |v| v.product }.uniq.where(scope) # end # def ProductFilters.parent_color_filter # parent_color_property = Spree::Property.find_by(name: 'Parent Color') # parent_color = parent_color_property ? Spree::ProductProperty.where(property_id: parent_color_property.id).pluck(:value).uniq.map(&:to_s) : [] # pp = Spree::ProductProperty.arel_table # conds = Hash[*parent_color.map { |b| [b, pp[:value].eq(b)] }.flatten] # { # name: 'Parent Color', # scope: :parent_color_any, # conds: conds, # labels: (parent_color.sort).map { |k| [k, k] } # } # end def ProductFilters.taxons_below(taxon) return Spree::Core::ProductFilters.all_taxons if taxon.nil? { name: 'Taxons under ' + taxon.name, scope: :taxons_id_in_tree_any, labels: taxon.children.sort_by(&:position).map { |t| [t.name, t.id] }, conds: nil } end # Filtering by the list of all taxons # # Similar idea as above, but we don't want the descendants' products, hence # it uses one of the auto-generated scopes from Ransack. # # idea: expand the format to allow nesting of labels? def ProductFilters.all_taxons taxons = Spree::Taxonomy.all.map { |t| [t.root] + t.root.descendants }.flatten { name: 'All taxons', scope: :taxons_id_equals_any, labels: taxons.sort_by(&:name).map { |t| [t.name, t.id] }, conds: nil } end end end end
json.array!(@cabins) do |cabin| json.extract! cabin, :id, :name, :available, :gender, :description, :max, :people_count json.url cabin_url(cabin, format: :json) end
require 'spec_helper' describe Codex::Loader do before do @path = 'minitest/etc/sample_journal.codex' @subject = Codex::Loader.new(@path) end def subject @subject end describe '#entries' do before do @entries = subject.entries end it 'has the right number of entries' do _(@entries.size).must_equal 3 @entries.each do |entry| _(entry).must_be_kind_of(Codex::Entry) end end end end
class WorkersController < ApplicationController load_and_authorize_resource param_method: :workers_params before_action :form_variables, only: [:new, :edit, :create, :update] def index if params[:workshop_id] @workers = Worker.accessible_by(current_ability).where(workshop_id: params[:workshop_id]) @workshop_id = params[:workshop_id] @total_expenses = 0 @total_income = 0 elsif params[:job_order_id] @job_order = JobOrder.find(params[:job_order_id]) @workshop = Workshop.find(@job_order.workshop_id) if params[:workshop] == 'seda' @workers = Worker.where(workshop_id: @workshop.id) elsif params[:workshop] == 'rsomat' @workers = Worker.where(workshop_id: @workshop.id, category: 'worker') end elsif params[:category] @workers = Worker.accessible_by(current_ability).where(category: params[:category]) else @workers= Worker.accessible_by(current_ability) end end def new @worker= Worker.new end def create @worker=Worker.new(workers_params) @worker.code = Worker.assign_serial(@worker.workshop_id) respond_to do |format| if @worker.save format.html { redirect_to workers_path} else format.html { render :new } end end end def edit @worker = Worker.find(params[:id]) end def update @worker = Worker.find(params[:id]) if @worker.update(workers_params) redirect_to workers_path else render 'edit' end end def destroy @worker = Worker.find(params[:id]) @worker.destroy redirect_to workers_path end private def workers_params params.require(:worker).permit(:name, :workshop_id, :hire_date, :address, :phone, :category, :rate_unit, :rate_amount, :fired, :firing_date) end def form_variables @workshops = Workshop.all end end
unless Rails.env.production? namespace :coveralls do desc 'Push latest coverage results to Coveralls.io' task push: :environment do require 'coveralls' Coveralls.push! end end end
class LiveLeagueMatch < ActiveRecord::Base validates_presence_of :players, :radiant_team, :dire_team, :lobby_id, :match_id, :league_id, :scoreboard validates_uniqueness_of :match_id end
class AddImageToPhoneBookEntry < ActiveRecord::Migration def change add_column :phone_book_entries, :image, :string end end
require 'spider/rules' module Spider class Agent attr_reader :schemes def schemes=(new_schemes) @schemes = new_schemes.map(&:to_s) end def visit_hosts @host_rules.accept end def visit_hosts_like(pattern=nil,&block) if pattern visit_hosts << pattern elsif block visit_hosts << block end return self end def ignore_hosts @host_rules.reject end def ignore_hosts_like(pattern=nil,&block) if pattern ignore_hosts << pattern elsif block ignore_hosts << block end return self end def visit_ports @port_rules.accept end def visit_ports_like(pattern=nil,&block) if pattern visit_ports << pattern elsif block visit_ports << block end return self end def ignore_ports @port_rules.reject end def ignore_ports_like(pattern=nil,&block) if pattern ignore_ports << pattern elsif block ignore_ports << block end return self end def visit_links @link_rules.accept end def visit_links_like(pattern=nil,&block) if pattern visit_links << pattern elsif block visit_links << block end return self end def ignore_links @link_rules.reject end def ignore_links_like(pattern=nil,&block) if pattern ignore_links << pattern elsif block ignore_links << block end return self end def visit_urls @url_rules.accept end def visit_urls_like(pattern=nil,&block) if pattern visit_urls << pattern elsif block visit_urls << block end return self end def ignore_urls @url_rules.reject end def ignore_urls_like(pattern=nil,&block) if pattern ignore_urls << pattern elsif block ignore_urls << block end return self end def visit_exts @ext_rules.accept end def visit_exts_like(pattern=nil,&block) if pattern visit_exts << pattern elsif block visit_exts << block end return self end def ignore_exts @ext_rules.reject end def ignore_exts_like(pattern=nil,&block) if pattern ignore_exts << pattern elsif block ignore_exts << block end return self end protected def initialize_filters(options={}) @schemes = [] if options[:schemes] self.schemes = options[:schemes] else @schemes << 'http' begin require 'net/https' @schemes << 'https' rescue Gem::LoadError => e raise(e) rescue ::LoadError warn "Warning: cannot load 'net/https', https support disabled" end end @host_rules = Rules.new( accept: options[:hosts], reject: options[:ignore_hosts] ) @port_rules = Rules.new( accept: options[:ports], reject: options[:ignore_ports] ) @link_rules = Rules.new( accept: options[:links], reject: options[:ignore_links] ) @url_rules = Rules.new( accept: options[:urls], reject: options[:ignore_urls] ) @ext_rules = Rules.new( accept: options[:exts], reject: options[:ignore_exts] ) if options[:host] visit_hosts_like(options[:host]) end end def visit_scheme?(scheme) if scheme @schemes.include?(scheme) else true end end def visit_host?(host) @host_rules.accept?(host) end def visit_port?(port) @port_rules.accept?(port) end def visit_link?(link) @link_rules.accept?(link) end def visit_url?(link) @url_rules.accept?(link) end def visit_ext?(path) @ext_rules.accept?(File.extname(path)[1..-1]) end end end
class AddDurationToEvents < ActiveRecord::Migration def change add_column :events, :duration, :interval end end
require 'rails_helper' describe Page do subject { create(:page, :reindex, content: '1234567890') } it 'can be searched' do subject expect(Page.search('1234567890').total_count).to eq(1) end it 'enqueues PageRelayJob on update only' do expect { subject }.to_not have_enqueued_job(PageRelayJob) expect { subject.update_attributes! content: 'ipsum' }.to have_enqueued_job(PageRelayJob) expect { subject.destroy }.to_not have_enqueued_job(PageRelayJob) end end
class Admin::AttachmentsController < Admin::BaseController def index @attachments = Attachment.paginate :page => params[:page], :per_page => @per_page, :order => "id DESC" end def show @attachment = Attachment.find(params[:id]) end def new @attachment = Attachment.new end def create @attachment = Attachment.new(params[:attachment]) if @attachment.save flash[:success] = "Successfully created File." redirect_to edit_admin_attachment_path(@attachment) else flash[:error] = "Could not crate File yet." render :action => 'new' end end def edit @attachment = Attachment.find(params[:id]) end def update @attachment = Attachment.find(params[:id]) if @attachment.update_attributes(params[:attachment]) flash[:success] = "Successfully updated File." redirect_to edit_admin_attachment_path(@attachment) else flash[:error] = "Could not update File." render :action => 'edit' end end def destroy @attachment = Attachment.find(params[:id]) if @attachment.item return_url = edit_admin_item_path(@attachment.item.id) else return_url = admin_attachments_url end @attachment.destroy flash[:success] = "Successfully destroyed File." redirect_to return_url 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). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Product.delete_all # . . . Product.create(title: 'Programming Ruby 1.9 & 2.0', description: %{<p> Ruby is the fastest growing and most exciting dynamic language out there. If you need to get working programs delivered fast, you should add Ruby to your toolbox. </p>}, image_url: 'ruby.jpg', price: 49.99) # . . . Product.create(title: 'Programming CoffeeScript 1.9 & 2.0', description: %{<p> CoffeeScript is a programming language that transcompiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python and Haskell in an effort to enhance JavaScript's brevity and readability. </p>}, image_url: 'cs.jpg', price: 35.99) # . . . Product.create(title: 'Ruby on Rails', description: %{<p> Ruby on Rails, or Rails, is a server-side web application framework written in Ruby under the MIT License. Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web pages. </p>}, image_url: 'rails.jpg', price: 55.99) # . . .
# Rubyには型が存在する # 例えば文字列型(String),整数型(Integer) puts "実行1" puts 5 puts "5" # 実行すると両方とも5と表示される # 同じ表示でも、「""」で囲うものと囲わないものでは意味が違ってくる puts "---------------------" puts "実行2" puts 5 + 3 puts "5 + 3" puts "5" + "3" # 実際の実行結果は # 8 # 5 + 3 # 53 # になる # ("")で囲ったものは、文字列型として扱われ、囲っていないものは、整数型として扱われる # 1行目は、整数型の計算である「5+3」が行われ、実行結果「8」が表示される # 2行目は、("")で囲われた「5+3」の文字が表示される # 3行目は、("")で囲われた文字列型の「5」と「3」を「+」で繋いでいるので、「5」と「3」が繋がって表示される # 文字列型同士が「+」で繋がれた場合、その文字列型を「結合する」処理が行われる puts "---------------------" puts "実行3" puts "I" + "am" + "Sam"
# frozen_string_literal: true require 'contracts/application_contract' require 'entities/coin' module Contracts module Coins class CreateCoinContract < ApplicationContract schema do required(:denomination) .filled(:string) .value(included_in?: Entities::Coin::DENOMINATIONS.keys) required(:state) .filled(:string) .value(included_in?: Entities::Coin::STATES) end end end end
class RegistrationsController < Devise::RegistrationsController before_action :one_user_registered?, only: [:new, :create] def new super end def create super end def update super end protected def one_user_registered? if User.count == 1 if user_signed_in? redirect_to root_path else redirect_to new_user_session_path end end end end
class ChargesController < ApplicationController def new end def create # Amount in cents @amount = 500 Stripe.api_key = Rails.application.secrets.secret_key token = params[:stripeToken] # Create the charge on Stripe's servers - this will charge the user's card once begin charge = Stripe::Charge.create( :amount => @amount, # amount in cents, again :currency => "cad", :source => token, :description => "Example charge" ) rescue Stripe::CardError => e # The card has been declined end # This should be done if recurring charges is needed. But it isn't required here. # If recurring charges (subscriptions) is needed see SubscriptionsController # customer = Stripe::Customer.create( # :email => params[:stripeEmail], # :source => token # :description => 'Creating a Stripe customer for future billing' # ) # begin # Can be used to call this charge repeatedly since customer has been created on stripe above and linked to # account in database through stripe_key as seen below BUT it isn't used for subscription plans # That is in a seperate SubscriptionsController # Can replace Stripe::Charge values with user input # charge = Stripe::Charge.create( # :customer => customer.id, # :amount => @amount, # :description => 'Rails Stripe customer', # :currency => 'cad' # :metadata => { order_id: '12345' } # Additional information to send to stripe for specific charge # ) # rescue Stripe::CardError => e # Card has been declined # end # Creating customer record in database with stripe_key for future payment # Can also be created through user input or better still on CustomerController # Customer.create!(customer_params) # This is just an example for elaboration - wouldn't actually work # Customer.create!( # first_name: 'client', # last_name: 'test', # email: params[:stripeEmail], # stripe_key: customer.id # ) end # protected # def customer_params # params.require(:user).permit(:stripeEmail, :first_name, :last_name, :stripe_key) # end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # module ActiveRecord module Associations class BelongsToPolymorphicAssociation < AssociationProxy #:nodoc: def replace(record) if record.nil? @target = @owner[@reflection.primary_key_name] = @owner[@reflection.options[:foreign_type]] = nil else @target = (AssociationProxy === record ? record.target : record) @owner[@reflection.primary_key_name] = record_id(record) @owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s @updated = true end loaded record end def updated? @updated end private def find_target return nil if association_class.nil? if @reflection.options[:conditions] association_class.find( @owner[@reflection.primary_key_name], :select => @reflection.options[:select], :conditions => conditions, :include => @reflection.options[:include] ) else association_class.find(@owner[@reflection.primary_key_name], :select => @reflection.options[:select], :include => @reflection.options[:include]) end end def foreign_key_present !@owner[@reflection.primary_key_name].nil? end def record_id(record) record.send(@reflection.options[:primary_key] || :id) end def association_class @owner[@reflection.options[:foreign_type]] ? @owner[@reflection.options[:foreign_type]].constantize : nil end end end end
require 'spec_helper' describe GroupDocs::Questionnaire::Collector do it_behaves_like GroupDocs::Api::Entity include_examples GroupDocs::Api::Helpers::Status subject do questionnaire = GroupDocs::Questionnaire.new described_class.new(:questionnaire => questionnaire) end describe '.get!' do before(:each) do mock_api_server(load_json('questionnaire_collector')) end it 'accepts access credentials hash' do lambda do described_class.get!('9fh349hfdskf', :client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'returns GroupDocs::Questionnaire::Collector object' do described_class.get!('9fh349hfdskf').should be_a(GroupDocs::Questionnaire::Collector) end end it { should have_accessor(:id) } it { should have_accessor(:guid) } it { should have_accessor(:questionnaire) } it { should have_accessor(:questionnaire_id) } it { should have_accessor(:type) } it { should have_accessor(:resolved_executions) } it { should have_accessor(:emails) } it { should have_accessor(:modified) } describe '#initialize' do it 'raises error if questionnaire is not specified' do lambda { described_class.new }.should raise_error(ArgumentError) end it 'raises error if questionnaire is not an instance of GroupDocs::Questionnaire' do lambda { described_class.new(:questionnaire => '') }.should raise_error(ArgumentError) end end describe '#type=' do it 'saves type in machine readable format if symbol is passed' do subject.type = :binary subject.instance_variable_get(:@type).should == 'Binary' end it 'does nothing if parameter is not symbol' do subject.type = 'Binary' subject.instance_variable_get(:@type).should == 'Binary' end end describe '#type' do it 'returns converted to human-readable format type' do subject.should_receive(:parse_status).with('Embedded').and_return(:embedded) subject.type = 'Embedded' subject.type.should == :embedded end end describe '#modified' do it 'returns converted to Time object Unix timestamp' do subject.modified = 1330450135000 subject.modified.should == Time.at(1330450135) end end describe '#add!' do before(:each) do mock_api_server(load_json('questionnaire_collectors_add')) subject.questionnaire = GroupDocs::Questionnaire.new end it 'accepts access credentials hash' do lambda do subject.add!(:client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'updates id and guid with response' do lambda do subject.add! end.should change { subject.id subject.guid } end end describe '#update!' do before(:each) do mock_api_server('{ "status": "Ok", "result": { "collector_id": 123456 }}') end it 'accepts access credentials hash' do lambda do subject.update!(:client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end end describe '#remove!' do before(:each) do mock_api_server('{ "status": "Ok", "result": {}}') end it 'accepts access credentials hash' do lambda do subject.remove!(:client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end end describe '#executions!' do before(:each) do mock_api_server(load_json('questionnaire_executions')) end it 'accepts access credentials hash' do lambda do subject.executions!(:client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'returns an array of GroupDocs::Questionnaire::Execution objects' do executions = subject.executions! executions.should be_an(Array) executions.each do |execution| execution.should be_a(GroupDocs::Questionnaire::Execution) end end end describe '#add_execution!' do before(:each) do mock_api_server(load_json('questionnaire_execution_add')) end let(:execution) { GroupDocs::Questionnaire::Execution.new } it 'accepts access credentials hash' do lambda do subject.add_execution!(execution, :client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'raises error if execution is not GroupDocs::Questionnaire::Execution object' do lambda { subject.add_execution!('Execution') }.should raise_error(ArgumentError) end it 'uses hashed version of execution along with executive payload' do execution.should_receive(:to_hash) subject.add_execution!(execution) end it 'returns GroupDocs::Questionnaire::Execution object' do subject.add_execution!(execution).should be_a(GroupDocs::Questionnaire::Execution) end end describe '#fill!' do before(:each) do mock_api_server(load_json('document_datasource')) end let(:datasource) do GroupDocs::DataSource.new(:id => 1) end it 'accepts access credentials hash' do lambda do subject.fill!(datasource, {}, :client_id => 'client_id', :private_key => 'private_key') end.should_not raise_error() end it 'accepts options hash' do lambda do subject.fill!(datasource, :new_type => :pdf) end.should_not raise_error() end it 'raises error if datasource is not GroupDocs::Datasource object' do lambda { subject.fill!('Datasource') }.should raise_error(ArgumentError) end it 'returns GroupDocs::Job object' do subject.fill!(datasource).should be_a(GroupDocs::Job) end end end
class Bookmark < ActiveRecord::Base belongs_to :user has_many :likes default_scope { order('created_at DESC') } end
require 'spec_helper' describe KitsController do describe "#index" do it "should display all the published kits and some featured programs" do kit = create(:kit, published: true) program = create(:program, featured: true) unpublished = create(:kit, published: false) get :index assigns(:kits).should == [kit] assigns(:programs).should == [program] end end end
RSpec.describe BidType do it { is_expected.to have_attribute :name } it { is_expected.to validate_uniqueness_of :name } it { is_expected.to validate_presence_of :name } end
# To finish the installation, you'll need to add it to your layout. I don't do that # here for fear of conflicts. # <!--[if lt IE 9]> # <script src="<%= javascript_include_tag "html5" %>"></script> # <![endif]--> after_bundler do # Get html5 shiv for IE, but don't require it - it will be included # inside a conditional comment get_vendor_javascript 'http://html5shiv.googlecode.com/svn/trunk/html5.js', 'html5' insert_into_precompilation_list 'html5.js' end __END__ name: Html5 Shiv description: Get HTML5 shiv to polyfill elements for older browsers website: https://code.google.com/p/html5shiv/ author: mattolson category: polyfill
post '/signup' do user = User.new(params[:user]) if user.save # what should happen if the user is saved? redirect "/home" else # what should happen if the user keyed in invalid date? # redirect '/' @email_message = user.errors.full_messages.join(',') erb :"/static/index" end end post '/login' do # find user with email # check password # session[:user_id] = user.id params.inspect user = User.find_by(email: params[:user][:email]) if user.nil? @login_email_message = "Email format incorrect" erb :"/static/index" elsif user.authenticate(params[:user][:password]) session[:user_id] = user.id redirect "/home" else @password_message = "wrong password" erb :"/static/index" end # apply an authentication method to check if a user has enter a valid email and password # if a user has successfully been authenticated, you can assign the current user id to a session. end get '/logout' do # kill a session when a user chooses to logout, for example, assign nil to a session. session[:user_id] = nil # redirect to the appropriate page redirect '/' end get '/users/:id' do @user = User.find(params[:id]) erb :"/static/profile" end
class API::V1::RootController < API::BaseController def index hash = {} if current_user hash.merge!({ :account => { :href => api_v1_user_url(current_user) } }) end respond_with hash.to_json end end
module Darky module Utils class << self def default_options { :adapter => :open4, :dir => File.expand_path(% . ) } end end module ClassMethods def attr_private_reader *args args.each { |o| attr_reader o or private o } end def delegate source, target, options = {} instance_eval do |*args, &block| define_method source do |*args, &block| if target.is_a? Symbol eval String target else target end.send source,*args, &block end end end end end end
class CreateHourlyForecasts < ActiveRecord::Migration def change create_table :hourly_forecasts do |t| t.integer :time t.text :summary t.text :icon t.float :precip_probability t.float :temperature t.float :humidity t.float :wind_speed t.float :visibility t.references :location t.timestamps null: false end end end
class Pitch < ActiveRecord::Base belongs_to :user has_many :comments has_many :external_links, as: :linkable has_many :votes, as: :votable validates :title, length: { maximum: 50 } validates :tagline, length: { maximum: 140 } validates :description, length: { maximum: 3000 } GRAVITY = 1.1 attr_accessor :num_votes def score self.votes.count / ((age/3600) + 2)**GRAVITY end def age Time.now - self.created_at end def video video = self.media video.gsub!("watch?v=", "embed/") return video end def self.best_pitches_since(cutoff_time) self.all.sort do |p1, p2| p2.score <=> p1.score self.joins(:votes).where("created_at >= ?", Time.zone.now.beginning_of_day).group("votable_id").order("count(votes.id) DESC") end end def self.sort_pitches(sort_type) if sort_type == "new" Pitch.order(created_at: :DESC) elsif sort_type == "top" Pitch.all.sort { |p1, p2| p2.votes.count <=> p1.votes.count } elsif sort_type == "most_discussed" Pitch.all.sort { |p1, p2| p2.comments.count <=> p1.comments.count } else Pitch.all.sort { |p1, p2| p2.score <=> p1.score } end end end
require 'i18n' require 'cinch' require 'openra/irc_bot/dictionary' require 'openra/irc_bot/plugins' module Openra class IRCBot < Cinch::Bot def self.load! return false if defined?(@loaded) Dictionary.add_path( File.join(__dir__, '../../', 'config', 'dictionaries') ) @loaded = true end def self.dict(key, **options) Dictionary.(key, **options) end def initialize(*) self.class.load! super end end end
require 'test_helper' class UpdatingShowsTest < ActionDispatch::IntegrationTest setup do @show = shows(:show1) @updated_name = 'Updated Show Display' end test 'valid -> status' do update_valid assert_equal 200, response.status end test 'valid -> type' do update_valid assert_equal Mime::JSON, response.content_type end test 'valid -> content' do update_valid assert_equal @updated_name, show_from_response[:display_name] end test 'valid -> record' do update_valid assert_equal @updated_name, @show.reload.display_name end test 'invalid -> status' do update_invalid assert_equal 422, response.status end def update_valid attributes = @show.attributes attributes[:display_name] = @updated_name put "/shows/#{@show.id}", { show: attributes }.to_json, request_headers.merge({ 'Content-Type' => 'application/json' }) end def update_invalid attributes = @show.attributes attributes[:display_name] = nil put "/shows/#{@show.id}", { show: attributes }.to_json, request_headers.merge({ 'Content-Type' => 'application/json' }) end def show_from_response json(response.body)[:show] end end
require 'formula' class GenymotionPeco < Formula homepage 'https://github.com/satoshun/genymotion-peco' url 'https://raw.githubusercontent.com/satoshun/genymotion-peco/4270def977473a48ed9feed97b035786a9585627/genymotion_peco' sha256 '2862ff209e0daaeeacfdbb211fa1f7686f2c5e094d2dcc638b6fa92ded2f0100' def install bin.install 'genymotion_peco' end end
class MarketCoin < ActiveRecord::Base # informations validates :symbol, presence: true validates :name, presence: true validates :coin_name, presence: true validates :code, presence: true, uniqueness: true validates :full_name, presence: true # image validates :logo_url, presence: false # details validates :algorithm, presence: true validates :proof_type, presence: true # numbers validates :market_cap, presence: true, numericality: true validates :price, presence: true, numericality: true validates :day_open, presence: true, numericality: true validates :day_high, presence: true, numericality: true validates :day_low, presence: true, numericality: true validates :all_time_high, presence: true, numericality: true # things that could be useful validates :rank, presence: false # trackings has_many :user_market_coins has_many :watchlist_coins # channel users has_one :market_coin_stream # NOTE : this will be replaced by a way # more effective system later on scope :search, -> (query) do where('(full_name ILIKE ?) OR (symbol ILIKE ?) OR (coin_name ILIKE ?) OR (name ILIKE ?)', "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%") end scope :default_order, -> do order(market_cap: :desc).order(rank: :asc) end scope :top, -> { order(rank: :asc).limit(8) } def price_variation (price / day_open - 1).to_f end def day_high_variation (day_high / day_open - 1).to_f end def day_low_variation (day_low / day_open - 1).to_f end end
namespace :check do namespace :migrate do desc "Forces re-index of ProjectMedias associated with a set of team_ids and optionally a start position for ProjectMedia IDs. Example: bundle exec rake check:migrate:reindex_alegre_text_project_medias['team-slug',last-project-media-id,model-name]" task :reindex_alegre_text_project_medias, [:slugs, :last, :model_name] => :environment do |_task, args| started = Time.now.to_i team_ids = BotUser.alegre_user.team_bot_installations.map(&:team_id).uniq.sort if args[:slugs] team_ids = Team.where(slug: args[:slugs].split(',')).map(&:id) end i = 0 last = args[:last].to_i model_name = args[:model_name] total = ProjectMedia.where(team_id: team_ids).where('created_at > ?', Time.parse('2020-01-01')).where('id > ?', last).count ProjectMedia.where(team_id: team_ids).where('created_at > ?', Time.parse('2020-01-01')).where('id > ?', last).order('id ASC').find_each do |pm| i += 1 if pm.is_text? threads = [] klass = Bot::Alegre ['analysis_title', 'analysis_description', 'original_title', 'original_description'].each do |field| threads << Thread.new do text = pm.send(field).to_s unless text.blank? doc_id = klass.item_doc_id(pm, field) klass.send_to_text_similarity_index(pm, field, text, doc_id, model_name) end end end threads.map(&:join) puts "[#{Time.now}] (#{i}/#{total}) Done for project media with ID #{pm.id}" else puts "[#{Time.now}] (#{i}/#{total}) Skipping non-text project media with ID #{pm.id}" end end minutes = (Time.now.to_i - started) / 60 puts "[#{Time.now}] Done in #{minutes} minutes." end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe LandlordsController, type: :controller do let(:current_user) { create(:user) } let(:session) { { user_id: current_user.id } } let(:params) { {} } describe 'PUT #update' do subject { put :update, params: params, session: session } let!(:landlord) { create(:landlord) } let(:property) { create(:property, landlord_email: landlord.email) } let(:params) { { id: landlord.id } } context 'when valid landlord param attributes' do let(:valid_landlord_attributes) do { first_name: 'somelandlordfirstname', last_name: 'somelandlordlastname', email: 'somelandlordemail@topfloor.ie' } end let(:params) { { id: landlord.id, landlord: valid_landlord_attributes } } it 'assigns @landlord' do subject expect(assigns(:landlord)).to be_a Landlord end it 'updates the Landlord' do subject landlord.reload property.reload expect(landlord.first_name).to eq valid_landlord_attributes[:first_name] expect(landlord.last_name).to eq valid_landlord_attributes[:last_name] expect(landlord.email).to eq valid_landlord_attributes[:email] expect(landlord.email).to eq property.landlord_email expect(landlord.try(:properties).count).to eq 1 end it 'responds with 302 Found' do subject expect(response).to have_http_status(:found) end it 'redirects to landlords#show' do subject expect(response).to redirect_to Landlord.last end it 'assigns flash success' do subject expect(flash[:success]).to eq I18n.t(:success_update, scope: 'controllers.landlords.messages', first_name: valid_landlord_attributes[:first_name], last_name: valid_landlord_attributes[:last_name], email: valid_landlord_attributes[:email]) end end context 'when invalid landlord param attributes' do let(:invalid_landlord_attributes) do { first_name: '', last_name: '', email: '' } end let(:params) { { id: landlord.id, landlord: invalid_landlord_attributes } } it 'does not update the Landlord' do expect { subject }.to_not(change { landlord.reload.attributes }) end it 'responds with unprocessable_entity' do subject expect(response).to have_http_status(:unprocessable_entity) end end context 'when user is not logged in' do subject { put :update, params: params, session: {} } it 'returns http forbidden status' do subject expect(response).to have_http_status(:forbidden) end it 'renders error page' do subject expect(response).to render_template('errors/not_authorized') end end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Users::List, type: :action do describe 'Inputs' do subject { described_class.inputs } it { is_expected.to be_empty } end describe 'Outputs' do subject { described_class.outputs } it { is_expected.to include(list: { type: Enumerable }) } end describe '#call' do subject(:result) { described_class.result } context 'when tier exists' do let!(:user) { create(:user) } it { is_expected.to be_success } it 'returns user list' do expect(result.list).to eq([user]) end end context 'when order doesn`t exist' do let!(:order) { Order.all.to_a } it 'returns order nil' do expect(result.list.to_a).to eq(order) end end end end
# frozen_string_literal: true class Artist < ActiveRecord::Base has_many :songs has_many :genres, through: :songs # extend Slugifiable::ClassMethods # include Slugifiable::InstanceMethods def slug name.downcase.split(" ").join("-") end def self.find_by_slug(slug) all.find { |artist| artist.slug == slug } end end
class Member < User has_many :workspace_users, foreign_key: :user_id has_many :workspaces, through: :workspace_users end
FactoryBot.define do factory :monthly_point do association :user, factory: :user points { 0 } start_date { Date.today.beginning_of_month } end_date { Date.today.end_of_month.end_of_day } end end
class CreateInstallments < ActiveRecord::Migration[5.2] def change create_table :installments do |t| t.integer :present_value t.decimal :number_of_installments t.decimal :monthly_interest_rate t.timestamps end end end
class PoorPokemon::Move attr_accessor :name, :dmg, :type, :pp def initialize (name, dmg, type, pp) @name = "#{name} (#{type})" @dmg = dmg @type = type @pp = pp end def usable? #returns true if move has enough PP to be used @pp>0 end end
# frozen_string_literal: true module Api # # jiman-api controller of the jimen # class JimenController < ApiController before_action :authenticated?, only: %i[create update] before_action :check_id, only: %i[show jump update] before_action :parse_json, only: %i[create update] def index @jimen = Jiman.all raise RecordNotFound, 'No records on jiman items' if @jimen.empty? render 'index', formats: :json, handlers: 'jbuilder' end def show @jiman = Jiman.find(@id) render 'show', formats: :json, handlers: 'jbuilder' end def list check_category_id @jimen = Jiman.includes(:categories) .where(categories: { id: @category_id }) raise RecordNotFound, 'No contents of jiman found' if @jimen.empty? render 'index', formats: :json, handlers: 'jbuilder' end def ulist check_user_id @jimen = Jiman.where(user_id: @user_id) raise RecordNotFound, 'No contents of jiman found' if @jimen.empty? @user = User.find(@user_id) raise RecordNotFound, 'Not found' if @user.nil? render 'ulist', formats: :json, handlers: 'jbuilder' end def update @jiman = Jiman.find_by(id: @id, user_id: @authed_user.id) raise RecordNotFound, 'Not found' if @jiman.nil? Jiman.save_jiman(@jiman, @authed_user.id, jiman_params) render 'show', formats: :json, handlers: 'jbuilder' end def create @jiman = Jiman.new Jiman.save_jiman(@jiman, @authed_user.id, jiman_params) render 'show', formats: :json, handlers: 'jbuilder' end def jump @jiman = Jiman.find(@id) raise RecordNotFound, 'Not found' if @jiman.nil? @jiman.increment_access render 'show', formats: :json, handlers: 'jbuilder' end private # Check parameter category_id def check_category_id @category_id = params[:category_id] return if @category_id =~ /^\d+$/ raise BadRequest, "Invalid category id: #{@category_id}" end # Check parameter user_id def check_user_id @user_id = params[:user_id] return if @user_id =~ /^\d+$/ raise BadRequest, "Invalid user id: #{@user_id}" end # Check parameter id def check_id @id = params[:id] return if @id =~ /^\d+$/ raise BadRequest, "Invalid jiman id: #{@id}" end # Parse jiman json data to params def parse_json params[:jiman] = JSON.parse(request.body.read, symbolize_names: true) end # Strong parameters def jiman_params params.require(:jiman).permit( :title, :description, :url, :point1, :point2, :point3, :point4, :point5, :point6, imagedata: %i[name type base64data], categories: [:id, :name] ) end end end
require 'vagrant' module Migrant module Provisioners class ChefSolo < Base include Util register :chef_solo def initialize(env) super end def prepare end def upload server = @environment.server vagrant_environment = Vagrant::Environment.new vagrant_provisioner_config = vagrant_environment.config.vm.provisioners.first.config cookbook_paths = vagrant_provisioner_config.cookbooks_path roles_path = vagrant_provisioner_config.roles_path # Delete old stuff server.ssh "rm -rf /tmp/migrant && mkdir -p /tmp/migrant" @environment.ui.info "Uploading Cookbooks" cookbook_dest_paths = [] cookbook_paths.each do |path| dest_path = "/tmp/migrant/#{File.basename(path)}" server.scp path, dest_path, :recursive => true cookbook_dest_paths << dest_path end role_dest_paths = [] dest_path = "/tmp/migrant/#{File.basename(roles_path)}" server.scp roles_path, dest_path, :recursive => true role_dest_paths << dest_path @environment.ui.info "Generating Chef Solo Config Files" File.open('/tmp/migrant-solo.rb','w') do |f| f.write(TemplateRenderer.render('chef/solo.rb', { :cookbook_path => cookbook_dest_paths, :role_path => role_dest_paths })) end server.scp "/tmp/migrant-solo.rb","/tmp/migrant/solo.rb" File.open('/tmp/migrant-dna.json','w') do |f| f.write(TemplateRenderer.render('chef/dna.json', { :run_list => vagrant_provisioner_config.run_list })) end server.scp "/tmp/migrant-dna.json","/tmp/migrant/dna.json" end def run @environment.cloud.execute(['sudo chef-solo -c /tmp/migrant/solo.rb -j /tmp/migrant/dna.json']) end end end end
class TeacherRelationship < ApplicationRecord belongs_to :teacher belongs_to :student end
require 'deviantart/base' module DeviantArt ## # Access token class for authorization code grant class AuthorizationCode::AccessToken < Base attr_accessor :expires_in, :status, :access_token, :token_type, :refresh_token, :scope end end
class UsersController < ApplicationController before_action :security, only: [:show, :favorites, :save_favorite, :destroy_favorite] def show @user = User.find(params[:id]) end def new @user = User.new() end def create @user = User.new(user_params) if @user.save() session[:user_id] = @user.id redirect_to songs_path else flash[:message] = "An error occurred upon login! \n Please try again." render :new end end def favorites #show users favorite songs @user = current_user end def save_favorite @user = current_user() #if song already exists in user favorites flash message and route back to songs index if !@user.songs.find_by(id: params[:id]) @favorite_song = Song.find_by(id: params[:id]) @user.songs << @favorite_song render :favorites else flash[:message] = "You've already favorited that song silly! \nPick a different song!" redirect_to songs_path end end def destroy_favorite @user = current_user() #Delete the join table link, not the song! @song_to_destroy = @user.favorite_songs.find_by(song_id: params[:id]) if @song_to_destroy.delete() render :favorites else flash[:message] = "Error when deleting item with id: #{params[:id]}" render :favorites end end private def user_params params.require(:user).permit(:email, :user_name, :user_pass) end end
class Identity < ActiveRecord::Base belongs_to :user, class_name: Spree::User, inverse_of: :identities validates :provider, inclusion: { in: %w(twitter facebook gplus) } end
require 'thor' require 'open-uri' require 'dashing/version' module Dashing class CLI < Thor include Thor::Actions attr_reader :name class << self attr_accessor :auth_token def hyphenate(str) return str.downcase if str =~ /^[A-Z-]+$/ str.gsub('_', '-').gsub(/\B[A-Z]/, '-\&').squeeze('-').downcase end end no_tasks do %w(widget dashboard job).each do |type| define_method "generate_#{type}" do |name| @name = Thor::Util.snake_case(name) directory(type.to_sym, "#{type}s") end end end desc "--version, -v", "Prints the version" map %w[--version -v] => :__print_version def __print_version say "#{Dashing::VERSION}" end desc "new PROJECT_NAME", "Sets up ALL THE THINGS needed for your dashboard project." def new(name) @name = Thor::Util.snake_case(name) directory(:project, @name) end desc "generate (widget/dashboard/job) NAME", "Creates a new widget, dashboard, or job." def generate(type, name) public_send("generate_#{type}".to_sym, name) rescue NoMethodError => _e puts "Invalid generator. Either use widget, dashboard, or job" end desc "install GIST_ID [--skip]", "Installs a new widget from a gist (skip overwrite)." def install(gist_id, *args) gist = Downloader.get_gist(gist_id) public_url = "https://gist.github.com/#{gist_id}" install_widget_from_gist(gist, args.include?('--skip')) print set_color("Don't forget to edit the ", :yellow) print set_color("Gemfile ", :yellow, :bold) print set_color("and run ", :yellow) print set_color("bundle install ", :yellow, :bold) say set_color("if needed. More information for this widget can be found at #{public_url}", :yellow) rescue OpenURI::HTTPError => _http_error say set_color("Could not find gist at #{public_url}"), :red end desc "start", "Starts the server in style!" method_option :job_path, :desc => "Specify the directory where jobs are stored" def start(*args) port_option = args.include?('-p') ? '' : ' -p 3030' args = args.join(' ') command = "bundle exec thin -R config.ru start#{port_option} #{args}" command.prepend "export JOB_PATH=#{options[:job_path]}; " if options[:job_path] run_command(command) end desc "stop", "Stops the thin server" def stop command = "bundle exec thin stop" run_command(command) end desc "job JOB_NAME AUTH_TOKEN(optional)", "Runs the specified job. Make sure to supply your auth token if you have one set." def job(name, auth_token = "") Dir[File.join(Dir.pwd, 'lib/**/*.rb')].each {|file| require_file(file) } self.class.auth_token = auth_token f = File.join(Dir.pwd, "jobs", "#{name}.rb") require_file(f) end # map some commands map 'g' => :generate map 'i' => :install map 's' => :start private def run_command(command) begin system(command) rescue Interrupt => _e say "Exiting..." end end def install_widget_from_gist(gist, skip_overwrite) gist['files'].each do |file, details| if file =~ /\.(html|coffee|scss)\z/ widget_name = File.basename(file, '.*') new_path = File.join(Dir.pwd, 'widgets', widget_name, file) create_file(new_path, details['content'], :skip => skip_overwrite) elsif file.end_with?('.rb') new_path = File.join(Dir.pwd, 'jobs', file) create_file(new_path, details['content'], :skip => skip_overwrite) end end end def require_file(file) require file end end end
class AddPositionToHiringCompany < ActiveRecord::Migration def change add_column :hiring_companies, :position, :integer end end
# Item Class class Item attr_reader :description attr_reader :price attr_reader :total_tax attr_reader :total_price attr_reader :tax_round def initialize(description, price, imported = false, tax_exempt = false) @description = description @price = price @imported = imported @tax_exempt = tax_exempt @import_tax = import_tax @sales_tax = sales_tax @total_tax = @import_tax + @sales_tax @total_price = @price + @total_tax end def import_tax if @imported == true return @price * 0.05 else return 0 end end def sales_tax if @tax_exempt == true return 0 else return @price * 0.10 end end def rounder(num) if (num * 100).to_i % 5 > 0 puts ((num * 100).to_i - ((num * 100).to_i % 5) + 5).to_f / 100 else puts num end end def item_details "#{@description} at #{@total_price}" end end
module Service class MessageList < BaseService step :query step :order def query Message.all.page(params.fetch('page', 1)).per(20) end def order result.order(created_at: :desc) end end end
module TinyMCE VERSION = "3.4.7" TINYMCE_VERSION = "3.4.7" end
class SessionsController < ApplicationController before_action :find_user, only: [:show, :index] skip_before_action :current_user def index # @user = User.find_by(id: params[:id]) if current_user && session[:user_id] @products_sold =[] orders_paid= Order.where(status: "paid") orders_paid.each do |po| po.order_items.each do |op| product = Product.find_by(id: op.product_id) if product.user_id == @user.id @products_sold << product end end end @total_revenue = 0 @products_sold.each do |product| @total_revenue += product.price end else flash[:status] = :failure flash[:result_text] = "You need to login in to see this page" redirect_to user_path end end def new @user = User.new end def create auth_hash = request.env['omniauth.auth'] if auth_hash['uid'] @user = User.find_by(uid: auth_hash['uid'], provider: 'github') if @user.nil? @user = User.info_from_github(auth_hash) if @user.save session[:user_id] = @user.id flash[:success] = "Successfully created new user #{@user.username} with ID #{@user.id}" else flash[:error] = "Could not log in" flash[:messages] = @user.errors.messages end else session[:user_id] = @user.id flash[:success] = "Successfully logged in #{@user.username} as existing user!" end session[:user_id] = @user.id else flash[:error] = "Could not authenticate user via Github" end redirect_to root_path end def logout if session[:user_id] session[:user_id] = nil flash[:result_text] = "Successfully logged out" redirect_to root_path end end # def destroy # session[:user_id] = nil # flash[:success] = "Successfully logged out!" # # redirect_to root_path # end private def find_user @user = User.find_by(id: params[:id]) render_404 unless @user end end
class Mahjong::Field::RiverSerializer < ApplicationSerializer has_many :tiles end
class AddIpAddressToAnonymousToken < ActiveRecord::Migration def self.up add_column :anonymous_tokens, :ip_address, :string add_index :anonymous_tokens, :ip_address end def self.down remove_index :anonymous_tokens, :ip_address remove_column :anonymous_tokens, :ip_address end end
class AllController < ApplicationController before_action :authenticate_user! def index @movies = current_user.movies.page(params[:page]).per(15) @shows = current_user.shows.page(params[:page]).per(15) end end
#!/usr/bin/env ruby def promtAndGet(prompt) print prompt str = gets.chomp throw :quitRequested if str == "!" return str end catch :quitRequested do name = promtAndGet("name:") age = promtAndGet("age:") sex = promtAndGet("sex:") puts name,age,sex end
class CreateCoins < ActiveRecord::Migration[6.1] def change create_table :coins do |t| t.string :coin_api_id t.string :name t.string :symbol t.string :image t.decimal :current_price t.decimal :price_change_percentage_1h_in_currency t.decimal :high_24h t.decimal :low_24h t.decimal :total_volume t.decimal :market_cap t.decimal :market_cap_rank t.decimal :circulating_supply t.timestamps end end end
module RedmineCharts module RangeUtils include Redmine::I18n @@types = [ :months, :weeks, :days ] @@days_per_year = 366 @@weeks_per_year = 53 @@months_per_year = 12 @@seconds_per_day = 86400 def self.types @@types end def self.options @@types.collect do |type| [l("charts_show_last_#{type}".to_sym), type] end end def self.default_range { :range => :weeks, :limit => 20, :offset => 0 } end def self.from_params(params) if params[:range] and params[:offset] and params[:limit] range = {} range[:range] = params[:range] ? params[:range].to_sym : :weeks range[:offset] = Integer(params[:offset]) range[:limit] = Integer(params[:limit]) range else nil end end def self.propose_range_for_two_dates(start_date, end_date) { :range => :days, :offset => (Date.today - end_date).to_i, :limit => (end_date - start_date).to_i + 1 } end def self.propose_range(start_date) if (diff = diff(start_date[:day], current_day, @@days_per_year)) <= 20 type = :days elsif (diff = diff(start_date[:week], current_week, @@weeks_per_year)) <= 20 type = :weeks else (diff = diff(start_date[:month], current_month, @@months_per_year)) type = :months end diff = 10 if diff < 10 { :range => type, :offset => 0, :limit => diff + 1} end def self.prepare_range(range) keys = [] labels = [] limit = range[:limit] - 1 if range[:range] == :days current, label = subtract_day(current_day, range[:offset]) keys << current labels << label limit.times do current, label = subtract_day(current, 1) keys << current labels << label end elsif range[:range] == :weeks current, label = subtract_week(current_week, range[:offset]) keys << current labels << label limit.times do current, label = subtract_week(current, 1) keys << current labels << label end else current, label = subtract_month(current_month, range[:offset]) keys << current labels << label limit.times do current, label = subtract_month(current, 1) keys << current labels << label end end keys.reverse! labels.reverse! range[:keys] = keys range[:labels] = labels range[:max] = keys.last range[:min] = keys.first range end private def self.format_week(date) date.strftime('%Y0%W') end def self.format_month(date) date.strftime('%Y0%m') end def self.format_day(date) date.strftime('%Y%j') end def self.format_date_with_unit(date, unit) case unit when :days format_day(date) when :weeks format_week(date) when :months format_month(date) end end def self.current_week format_week(Time.now) end def self.current_month format_month(Time.now) end def self.current_day format_day(Time.now) end def self.date_from_week(year_and_week_of_year) Date.strptime(year_and_week_of_year, "%Y0%W") end def self.date_from_month(year_and_month) Date.strptime(year_and_month, "%Y0%m") end def self.date_from_day(year_and_day_of_year) Date.strptime(year_and_day_of_year, "%Y%j") end def self.date_from_unit(date_string, unit) case unit when :days date_from_day(date_string) when :weeks date_from_week(date_string) when :months date_from_month(date_string) end end def self.diff(from, to, per_year) year_diff = to.to_s[0...4].to_i - from.to_s[0...4].to_i diff = to.to_s[4...7].to_i - from.to_s[4...7].to_i (year_diff * per_year) + diff end def self.subtract_month(current, offset) date = date_from_month(current) - offset.months [date.strftime("%Y0%m"), date.strftime("%b %y")] end def self.subtract_week(current, offset) date = Date.strptime(current, "%Y0%W") - offset.weeks key = "%d%03d" % [date.year, date.strftime("%W").to_i] date -= ((date.strftime("%w").to_i + 6) % 7).days day_from = date.strftime("%d").to_i month_from = date.strftime("%b") year_from = date.strftime("%y") date += 6.days day_to = date.strftime("%d").to_i month_to = date.strftime("%b") year_to = date.strftime("%y") if year_from != year_to label = "#{day_from} #{month_from} #{year_from} - #{day_to} #{month_to} #{year_to}" elsif month_from != month_to label = "#{day_from} #{month_from} - #{day_to} #{month_to} #{year_from}" else label = "#{day_from} - #{day_to} #{month_from} #{year_from}" end [key, label] end def self.subtract_day(current, offset) date = Date.strptime(current, "%Y%j") - offset key = "%d%03d" % [date.year, date.yday] [key, date.strftime("%d %b %y")] end end end
class AddAuditReports < ActiveRecord::Migration def up create_table :audit_reports do |t| t.references :user, type: :uuid t.integer :wegoaudit_id t.string :name t.json :data t.timestamps end add_foreign_key :audit_reports, :users end def down drop_table :audit_reports end end
class UserEvent < ApplicationRecord belongs_to :attended_event, class_name: 'Event' belongs_to :event_attender, class_name: 'User' end
# Require core library require "middleman-core" # Extension namespace module Middleman module Swiftype class << self attr_accessor :swiftype_options end class Options < Struct.new(:api_key, :engine_slug, :pages_selector, :process_html, :generate_sections, :generate_info, :generate_image, :title_selector, :should_index); end # For more info, see https://middlemanapp.com/advanced/custom_extensions/ class Extension < Middleman::Extension # config_name, default_value, description, required : true or false option :api_key, '', 'API key for swiftype', required: true option :engine_slug, '', 'Engine slug for switype', required: true option :pages_selector, '', 'Pages selector method call' option :title_selector, false, 'Title selector method call' option :process_html, false, 'Process html method call' option :generate_sections, false, 'Generate section method call' option :generate_info, '', 'Generate info method call' option :generate_image, false, 'Generate image method call' option :should_index, false, 'Should index method call' # create app.swiftype def swiftype(options=nil) @_swiftype ||= Struct.new(:options).new(options) end def initialize(app, options_hash={}, &block) super options = Options.new(options_hash) yield options if block_given? options.pages_selector ||= lambda { |p| p.path.match(/\.html/) && p.template? && !p.directory_index? } end def after_configuration swiftype(options) # swiftype_options are saved as a class attribute when middleman configurations are loaded ::Middleman::Swiftype.swiftype_options = options end def after_build(builder) helper = MiddlemanSwiftypeHelper.new app, options helper.generate_search_json end end end end
class AccountsController < ApplicationController STEPS = [:adapter, :keychain, :key, :remote] private def init_wizard puts "starting new wizard" session[:new_account] = {} end def store(step, data) session[:new_account][step.to_sym] = data pp session[:new_account] end def fetch(step) session[:new_account][step.to_sym] end def next_step next_step = (STEPS - session[:new_account].keys).first redirect_to :action => (next_step ? next_step : :complete) end public def index init_wizard next_step end def adapter if request.post? store(:adapter, params[:id]) next_step end end def keychain if request.post? store(:keychain, params[:id]) next_step end end def key if request.post? key = params[:key] # test key here ... store(:key, key) next_step end end def remote if request.get? adapter = Adapter.find(fetch(:adapter)) keychain = Keychain.find(fetch(:keychain)) key = fetch(:key) @accounts = adapter.list(keychain.details(key)) elsif request.post? store(:remote, params[:id]) next_step end end def complete # save # wipe - init_wizard # redirect to accounts list? @user.accounts.create( :external_id => fetch(:remote), :keychain_id => fetch(:keychain), :adapter_id => fetch(:adapter), :name => "new account" ) init_wizard end end
class TowersofHanoi attr_accessor :towers def initialize(towers = nil) towers.nil? ? populate_board(3) : @towers = towers # @disks = disks end def populate_board(disks) @towers = Array.new(3) { [] } (1..disks).each do |i| @towers[0].unshift(i) end end def move(string=nil) if string.nil? p "Please enter a move like: '#,#'" string = STDIN.gets.chomp end start, ending = string.split(",").map(&:to_i) unless @towers[ending].empty? raise "incorrect move" if @towers[start].last > @towers[ending].last end @towers[ending] << @towers[start].pop end def won? return false if @towers[0].any? if state = @towers.map {|el| el.size }.count {|el| el == 0} == 2 return true end false end def display p "#{@towers}" end end if __FILE__ == $PROGRAM_NAME game = TowersofHanoi.new until game.won? game.move game.display end end
require 'test_helper' class LikeCourseControllerTest < ActionDispatch::IntegrationTest setup do @user = users(:example) log_in_as(@user) @course = courses(:one) @like = like_courses(:one) end test "like should be valid" do assert_not @like.valid? end end
require 'json' require 'uri' require 'net/http' require 'openssl' module ThreeScale module API class HttpClient attr_reader :endpoint, :admin_domain, :provider_key, :headers, :format, :keep_alive def initialize(endpoint:, provider_key:, format: :json, verify_ssl: true, keep_alive: false) @endpoint = URI(endpoint).freeze @admin_domain = @endpoint.host.freeze @provider_key = provider_key.freeze @http = Net::HTTP.new(admin_domain, @endpoint.port) @http.use_ssl = @endpoint.is_a?(URI::HTTPS) @http.verify_mode = OpenSSL::SSL::VERIFY_NONE unless verify_ssl @headers = { 'Accept' => "application/#{format}", 'Content-Type' => "application/#{format}", 'Authorization' => 'Basic ' + [":#{@provider_key}"].pack('m').delete("\r\n") } if debug? @http.set_debug_output($stdout) @headers['Accept-Encoding'] = 'identity' end @headers.freeze @format = format @keep_alive = keep_alive end def get(path, params: nil) @http.start if keep_alive && !@http.started? parse @http.get(format_path_n_query(path, params), headers) end def patch(path, body:, params: nil) @http.start if keep_alive && !@http.started? parse @http.patch(format_path_n_query(path, params), serialize(body), headers) end def post(path, body:, params: nil) @http.start if keep_alive && !@http.started? parse @http.post(format_path_n_query(path, params), serialize(body), headers) end def put(path, body: nil, params: nil) @http.start if keep_alive && !@http.started? parse @http.put(format_path_n_query(path, params), serialize(body), headers) end def delete(path, params: nil) @http.start if keep_alive && !@http.started? parse @http.delete(format_path_n_query(path, params), headers) end # @param [::Net::HTTPResponse] response def parse(response) case response when Net::HTTPUnprocessableEntity, Net::HTTPSuccess then parser.decode(response.body) when Net::HTTPForbidden then forbidden!(response) when Net::HTTPNotFound then notfound!(response) else unexpected!(response) end end class ForbiddenError < ResponseError; end class UnexpectedResponseError < ResponseError; end class NotFoundError < ResponseError; end class UnknownFormatError < StandardError; end def forbidden!(response) raise ForbiddenError.new(response, format_response(response)) end def notfound!(response) raise NotFoundError.new(response, format_response(response)) end def unexpected!(response) raise UnexpectedResponseError.new(response, format_response(response)) end def unknownformat! raise UnknownFormatError, "unknown format #{format}" end def serialize(body) case body when nil then nil when String then body else parser.encode(body) end end def parser case format when :json then JSONParser else unknownformat! end end protected def debug? ENV.fetch('THREESCALE_DEBUG', '0') == '1' end # Helper to create a string representing a path plus a query string def format_path_n_query(path, params) path = "#{path}.#{format}" path << "?#{URI.encode_www_form(params)}" unless params.nil? path end def format_response(response) body = response.body if text_based?(response) "#{response.inspect} body=#{body}" end def text_based?(response) response.content_type =~ /^text/ || response.content_type =~ /^application/ && !['application/octet-stream', 'application/pdf'].include?(response.content_type) end module JSONParser module_function def decode(string) case string when nil, ' '.freeze, ''.freeze then nil else ::JSON.parse(string) end end def encode(query) ::JSON.generate(query) end end end end end
module ApplicationHelper def conditional_link_to(title, url, action, model) link_to title, url if can? action, model end def conditional_link_to_remote(title, url, action, model) link_to title, url, :remote => true if can? action, model end def conditional_link_to_delete(title, url, action, model) link_to title, url, :method => :delete, :data => { :confirm => "Are you sure you want to delete this? This action is irreversible." } if can? action, model end def text_with_conditional_link_to(title, url, action, model) if can? action, model link_to title, url else title end end def show_admin_link can? :read, Equipment or can? :read, Location or can? :read, Timecard or can? :read, InvoiceItem or can? :read, EmailForm or can? :read, Blackout end Date.class_eval do def ago return "today" if Date.today-self == 0 return "yesterday" if Date.today-self == 1 return "tomorrow" if Date.today-self == -1 return (Date.today-self).to_s+" days ago" if Date.today-self > 0 return "in "+(self-Date.today).to_s+" days" if Date.today-self < 0 end end def app_version if Rails.env.development? begin %x{git log --pretty=format:"%h" -n1} rescue "?" end else File.read(Rails.root.join("REVISION"))[0..6] end end def better_select_date(startdate, object, field) return select_year(startdate, :prefix => "#{object}[#{field}(1i)]", :discard_type => true) + select_month(startdate, :prefix => "#{object}[#{field}(2i)]", :discard_type => true) + select_day(startdate, :prefix => "#{object}[#{field}(3i)]", :discard_type => true) end def link_to_remove_fields(name, f, destroyable=false) if destroyable f.hidden_field(:_destroy) + link_to(name, "#", class: "destroyable delete_field", onClick: "return false") else f.hidden_field(:_destroy) + link_to(name, "#", class: "undestroyable delete_field", onClick: "return false") end end def link_to_add_fields(name, f, association, extra="", controller="", locals={}) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(controller + "/" + association.to_s.singularize + "_fields", locals.merge(:f => builder)) end link_to(name, "#", class:"add_field"+extra, data: {association: "#{association}", content: "#{fields}"}, onClick: "return false") end def link_to_add_eventdate_fields(name, f) new_object = f.object.class.reflect_on_association(:eventdates).klass.new new_object.event_roles.build fields = f.fields_for(:eventdates, new_object, :child_index => "new_eventdates") do |builder| render("events/eventdate_fields", {:f => builder}) end link_to(name, "#", class:"add_field", data: {association: "eventdates", content: "#{fields}"}, onClick: "return false") end end