text
stringlengths
10
2.61M
class CardController < ApplicationController require "payjp" def new card = Card.where(user_id: current_user.id) redirect_to card_show_path(current_user.id) if card.exists? end def create Payjp.api_key = Rails.application.credentials[:PAYJP_SECRET_KEY] if params["payjp_token"].blank? ...
class Category < ActiveRecord::Base has_many :pingas has_many :user_categories has_many :users, through: :user_categories validates :title, uniqueness: true end
require "bundler/capistrano" set :whenever_command, "bundle exec whenever" require "whenever/capistrano" default_run_options[:pty] = true set :application, "govsgo.com" role :app, application role :web, application role :db, application, :primary => true set :user, "rbates" set :dep...
require 'rails_helper' RSpec.describe Sword::Parsers::MetsParser do context "API/interface" do it 'has #parse method that takes file to parse' do expect(subject).to respond_to(:parse).with(1).arguments end it 'has #flocat_xlink_href attr_reader' do expect(subject).to respond_to(:flocat_xlink...
require 'rails_helper' RSpec.describe Purchase do describe '#gross_revenue' do let(:purchase) { build(:purchase, item_price: 20.0, purchase_count: 3) } it { expect(purchase.gross_revenue).to eq(60.0) } end end
class HomeController < ApplicationController def index @active_top_nav_link = :home @posts = Post.blog_posts.viewable render layout: "community" end end
class ApplicationMailer < ActionMailer::Base default from: "yourmail@naver.com" layout 'mailer' end
require_relative '../../automated_init' context "CLI" do context "Parse Arguments" do context "Exclude File Pattern" do pattern_text = Controls::Pattern.text control_pattern = Controls::Pattern.example context "Short Form" do parse_arguments = CLI::ParseArguments.new(['-x', pattern_tex...
require 'json' require 'rest_client' # CLOJURE # Maven central: http://central.maven.org/maven2/org/clojure/clojure/ # Source: Versioneye class Clojure def latest_stable response = RestClient.get("https://www.versioneye.com/api/v2/products/java/org~clojure:clojure?api_key=91780ca596c2e1906a9d") data = JSON.pa...
require 'rails_helper' RSpec.describe "contacts/new", :type => :view do before(:each) do assign(:contact, Contact.new( :first_name => "MyString", :last_name => "MyString", :age => 1, :gender => "MyString", :ethnicity => "MyString", :description => "MyText", :contactable_...
class MessagesController < ApplicationController def create message = Message.create(message_params) associated_chat = Chat.find_by(id: message.chat_id) MessageChannel.broadcast_to(associated_chat, message) #render json: @message end private def message_params params.require(:message).pe...
module ApplicationHelper class TargetBlankRenderer < Redcarpet::Render::HTML def initialize(extensions = {}) super extensions.merge(link_attributes: { target: '_blank' }) end end def logo(path, options = {}) processed_path = if path.nil? ENV['LOGO'] e...
class AddStuffToProjects < ActiveRecord::Migration[5.1] def change add_column :projects, :description, :string add_column :projects, :post_date, :string add_column :projects, :image, :string add_column :projects, :company, :string add_column :projects, :location, :string add_column...
require File.dirname(__FILE__) + '/../test_helper' require 'calendar_advs_controller' # Re-raise errors caught by the controller. class CalendarAdvsController; def rescue_action(e) raise e end; end class CalendarAdvsControllerTest < Test::Unit::TestCase fixtures :calendar_advs def setup @controller = Calenda...
$LOAD_PATH.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'topograf/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |gem| gem.name = 'topograf' gem.version = Topograf::VERSION gem.authors = ['Eric Helms'] gem.email = [...
class Attachment < ActiveRecord::Base belongs_to :user delegate :name, to: :user, prefix: "user" end
# coding:utf-8 class McGuffin ITEM_ANBIGUOUS = %w(もの 何か 謎 秘宝 宝物 お宝) ITEM_CODENAME = %w(鷹) ITEM_CONTAINERS = %w(壷 スーツケース アタッシュケース 財布 鞄 旅行鞄 スポーツバッグ ショルダーバッグ バックパック ナップサック リュックサック ハンドバッグ 袋 布袋 革袋 ゴミ袋 ビニール袋 コンビニのビニール袋 紙袋 麻袋 ...
# == Schema Information # # Table name: media # # id :string primary key # app :string(100) # context :string(100) # locale :string(10) # tags :string # content_type :string(100) # url :string # name :string(100) # lock_version :integer ...
FactoryBot.define do factory :image do title { ['Test title'] } alternate_title { ['Alternate Title 1'] } rights_statement { ['http://rightsstatements.org/vocab/NKC/1.0/'] } description { ['Test description'] } visibility { Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC } ab...
require 'spec_helper' describe "voluntarios/index" do before(:each) do assign(:voluntarios, [ stub_model(Voluntario, :nome => "Nome", :prontuario => "Prontuario", :sexo => 1, :estado_civil => 2, :profissao => "Profissao", :email => "Email", :nacionali...
require_relative '../errors/prestacion_not_exists_error' require_relative '../errors/centro_inexistente_error' require_relative '../errors/centro_ya_contiene_prestacion_error' HealthAPI::App.controllers :prestaciones, parent: :centros do get :index do centro = CentroRepository.new.full_load(params[:centro_id]) ...
## # This module requires Metasploit: http//metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'digest/md5' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient def initialize(info={}) super(...
# @author Kristian Mandrup # # Many role storage for storing multiple Role references on the role subject # # @note all methods potentially operate directly on values in the data store # module Troles::Storage class JoinRefMany < RefMany def initialize role_subject super end end end
module StrokeDB module Associations module HasMany include Base # # class WebSite # has_many :pages # has_many :reviews, :as => :reviewable_object # has_many :visits # has_many :visitors, :through => :visits # def has_many(slotname, options = {}, &bl...
require 'open-uri' require 'hpricot' namespace :data do namespace :import do desc 'Fetches 311 Service Requests from DC Gov. 311 Atom Feed' task :feed, :needs => :environment do rss = SimpleRSS.parse open('http://data.octo.dc.gov/feeds/src/src_current.xml') rss.items.each do |item| c...
# frozen_string_literal: true RSpec.describe SXS, '#configure' do it 'yields the default config' do described_class.configure do |conf| expect(conf).to be_a_instance_of SXS::Config end end end
#encoding: utf-8 class Contact include Mongoid::Document include Mongoid::Timestamps field :content, type: String validates :content, presence: true end
namespace :autocomplete_select do desc "Install assets for AutocompleteSelect in public directory" task :install_assets => :environment do require 'fileutils' dest = "#{RAILS_ROOT}/public/javascripts/autocomplete_select" FileUtils.mkdir_p dest FileUtils.cp "#{File.dirname(__FILE__)}/../../assets/aut...
module UsersHelper # Returns the Gravatar (http://gravatar.com/) for the given user. def gravatar_for(user, options = { size: 50 }) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) size = options[:size] gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}" image_tag(...
class CoursesController < ApplicationController def show @course = Course.find(params[:code]) end def new; end def create @course = Course.create(course_params) render :show end private def course_params params.permit(:name, :description, :enrollment_deadline, :code, :price, :instructo...
require 'rails_helper' RSpec.describe Permission, type: :model do let!(:user) { FactoryGirl.create(:user) } before { @permission = Permission.new(name:'admin', user: user) } subject { @permission} it { should respond_to :name } it { should respond_to :user } describe "when name is blank" do before ...
arg :aws_account desc 'Audits Reserved Instance Counts' command 'audit' do |c| c.switch [:e, :ec2], :desc => "Only audit EC2 instances" c.switch [:d, :rds], :desc => "Only audit RDS instances" c.switch [:c, :cache], :desc => "Only audit ElastiCache instances" c.switch [:r, :reserved], :desc => "Shows reserved i...
class Ticket < ApplicationRecord has_many :inquiries, dependent: :destroy belongs_to :user mount_uploader :image, AvatarUploader end
require 'sumac' # make sure it exists describe Sumac::Calls::RemoteCalls do def build_remote_calls connection = instance_double('Sumac::Connection') calls = Sumac::Calls::RemoteCalls.new(connection) end # ::new example do connection = instance_double('Sumac::Connection') calls = Sumac::Calls:...
# frozen_string_literal: true require_relative 'login_base_page' class SignInPage < LoginBasePage uri '/sign_in' end
require 'computer_player' describe ComputerPlayer do subject(:computer) { described_class.new } describe 'defaults' do it 'should initialize with a rock' do expect(computer.choice).to eq :rock end it 'should initialize with a name' do expect(computer.name).to eq 'The Computer' end ...
require 'rails_helper' describe Item do describe "#perform_clearance!" do let(:wholesale_price) { 100 } let(:item) { FactoryGirl.create(:item, style: FactoryGirl.create(:style, wholesale_price: wholesale_price)) } before do item.clearance! item.reload end it "should mark the item st...
module L10n class Translation attr_accessor :original, :translated, :comment include Comparable def initialize(original, translated, comment=nil) self.original = original self.translated = translated self.comment = comment end def original=(original) @original = pro...
class Shelter attr_accessor :adoptable_animals, :client_list def initialize @adoptable_animals = {} @client_list = {} end def list_clients end end class Client attr_accessor :name, :age, :gender, :kids, :number_of_pets def initialize(name, age, gender, kids, number_of_pets) @name = name ...
# Sale Class require './far_mar' class FarMar::Sale < FarMar::Shared attr_reader :id, :amount, :purchase_time, :vendor_id, :product_id # Reading in the associated csv file for this class and storing it in a # constant (for efficency) SALES_DATA = CSV.read("./support/sales.csv") def initialize(sale_hash) ...
# spec/controllers/routing_controller_spec.rb require 'spec_helper' require 'controllers/proxy_controller_helper' require 'controllers/mixins/callback_helpers_helper' require 'controllers/mixins/help_actions_helper' require 'controllers/mixins/module_helpers_helper' require 'controllers/mixins/user_helpers_helper' re...
module ClinkCloud class DataCenterMapping include Kartograph::DSL kartograph do mapping DataCenter property :id, scopes: [:read] property :name, scopes: [:read] property :links, scopes: [:read] end end end
require 'securerandom' class Fallout attr_reader :refined_list def initialize(complexity = 1, wordlist = ['hello', 'world']) @complexity = set_complexity(complexity) @wordlist = wordlist refine_wordlist complexity set_word end def refine_wordlist(complexity) complexity_match = ...
class PagesController < ApplicationController include HighVoltage::StaticPage before_action :assign_content_path, :except => [:robots] def robots render :text => File.read("config/robots.#{ Rails.env }.txt"), :layout => false, :content_type => 'text/plain' end private def assign_content_path Hig...
module Jelastic class Node attr_accessor :count, :fixed_cloudlets, :flexible_cloudlets, :display_name, :type def initialize yield(self) if block_given? end def with_public_ip @public_ip = true end def public_ip? @public_ip end def docker? @type == 'docker' ...
def english_number(n) if n < 0 # no negative numbers return "Please enter a number that isn't negative" end if n == 0 return "zero" end word = "" ones = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tens = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty...
class CommentsController < ApplicationController before_action :set_comment, only: [:destroy] def index @comments = Comment.all end def new @comment = Comment.new end def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(comment_params) respond_to do |format|...
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string(255) # email :string(255) # created_at :datetime not null # updated_at :datetime not null # class User < ActiveRecord::Base attr_accessible :name, :avatar, :email, :pass...
begin require 'rspec/core' require 'rspec/core/rake_task' namespace :check do thing_we_are_checking = :internals file_pattern = 'spec/**/*_spec.rb' RSpec::Core::RakeTask.new(thing_we_are_checking) do |spec| spec.pattern = FileList[file_pattern] spec.rspec_opts = "-cfd --tag ~wip --tag ~...
# Implementing Scrabble Score class Scrabble SCORE_TABLE = { 'A' => 1, 'B' => 3, 'C' => 3, 'D' => 2, 'E' => 1, 'F' => 4, 'G' => 2, 'H' => 4, 'I' => 1, 'J' => 8, 'K' => 5, 'L' => 1, 'M' => 3, 'N' => 1, 'O' => 1, 'P' => 3, 'Q' => 10, 'R' => 1, 'S' => 1, 'T' => 1, 'U' => 1, 'V' => 4, 'W' => 4, 'X' =>...
require 'rails_helper' RSpec.describe "Users Endpoints", type: :request do describe "POST users" do context "with a valid username" do let(:create_user) { post users_url(username: 'test_user') } it "returns http success" do create_user expect(response).to have_http_status(:success) ...
require 'spec_helper' describe OpenWeatherMaps do context 'Testing of forecast data' do before(:all) do @api_key = ENV['API_KEY'] @forecast_data = OpenWeatherMaps.new.forecast @forecast_data.retrieve('524901', @api_key) end it 'should return cod to be a string' do expect(...
module Cultivation class DestroyTask prepend SimpleCommand attr_reader :args def initialize(current_user, task_id) if task_id.nil? raise 'Invalid Task id' else @task_id = task_id end @current_user = current_user end # TODO : need to add workday check ...
# == Schema Information # Schema version: 57 # # Table name: admins # # id :integer(11) not null, primary key # login :string(255) # email :string(255) # name_first :string(255) # name_middle :string(255)...
module Google module Csene class Client TOKEN_CREDENTIAL_URI = 'https://accounts.google.com/o/oauth2/token' AUDIENCE = 'https://accounts.google.com/o/oauth2/token' SCOPE = 'https://www.googleapis.com/auth/cse' def initialize(application_name: 'google-csene', applicati...
# Exercise: Bonus Exercise #4 # Build a tic-tac-toe game on the command line where two human players can play against each other and the board is displayed in between turns. # Try using classes to structure your code. What are the different classes needed here? What are the instance variables? What are the instance m...
class MessagesController < ApplicationController def create @message = Message.new(message_params) @founder_conversation = FounderConversation.find(params[:founder_conversation_id]) @message.founder_conversation = @founder_conversation @message.user = current_user if @message.save @message....
FactoryGirl.define do factory :user do name "Saul Gausin" email "saul.gausin@gmail.com" password "foobar" password_confirmation "foobar" end end
require 'set' class RoverPosition attr_reader :x, :y def initialize(x,y) @x=x @y=y end def == other @x == other.x and @y == other.y end alias eql? == def hash @x + 37*@y end def + other RoverPosition.new @x + other.x, @y + other.y end end class RoverOrientation attr_reader :c...
class ApplicationController < ActionController::API # solution_for # undefined method `respond_with' include CanCan::ControllerAdditions include ActionController::ImplicitRender include ActionController::MimeResponds # solution_for # https://github.com/thoughtbot/clearance/issues/435 # Undefined method ...
require 'rails_helper' # RSpec.describe User, type: :model do # context 'validation tests' do # it 'ensures first name presence' do # user=User.new(lastname: 'senthil', email: 'sumii@gmail.com').save # expect(user).to eq(true) # end # it 'ensures last name presence' do # user=User.new(...
# frozen_string_literal: true Rails.application.routes.draw do resources :transactions, only: %i[show index create new] devise_for :users root 'transactions#index' end
class Brand < ActiveRecord::Base include Elasticsearch::Model include Elasticsearch::Model::Callbacks include ESModel include PublicActivity::Model tracked paginates_per 100 has_many :categories has_many :items belongs_to :category acts_as_punchable acts_as_taggable_on :states, :categories m...
#!/usr/bin/env ruby class Fixnum def pong() x = 0 input_array = [] while (x < self) x += 1 if (x % 15 === 0) input_array.push('pingpong') elsif (x % 3 === 0) input_array.push('ping') elsif (x % 5 === 0) input_array.push('pong') else input_arra...
require 'open-uri' require 'rexml/document' require 'json' class MusicBrainz URL = "http://www.musicbrainz.org/ws/2" ART_URL = "http://coverartarchive.org/release" include Cache def cover_art(artist, title) if mbid = release(artist, title) # TODO Cache this JSON response if raw = Http.get("#{A...
class Transaction < ApplicationRecord belongs_to :borrower, class_name: "User" belongs_to :book_item, class_name: "BookItem" belongs_to :transaction_status validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0} validates_presence_of :borrower, :book_item va...
class RequestLoanPage < SitePrism::Page set_url 'requestloan.htm' element :amount, "#amount" element :down_payment, "#downPayment" element :apply_now_btn, "input[value='Apply Now']" def submit_form apply_now_btn.click end def fill_form_but(field_name, amount_value, ...
# frozen_string_literal: true # Represents a Group's stored information class Song < Sequel::Model many_to_one :search def artists=(artists_plain) self.artists_secure = SecureDB.encrypt(artists_plain) end def artist SecureDB.decrypt(artists_secure) end end
# frozen_string_literal: true module BPS module PDF class Receipt < Base MODULES = %w[ CustomerInfo TransactionInfo Cost PolicyLinks ].freeze MODULES.each { |c| include "BPS::PDF::Receipt::#{c}".constantize } def self.create_pdf(payment) path = BPS::PDF::Receipt.generate...
require_relative 'test_helper' require_relative '../lib/round' class RoundTest < Minitest::Test def test_new_instance card_1 = Card.new(question: "What is the capital of Alaska?", answer: "Juneau") card_2 = Card.new(question: "Approximately how many miles are in one astronomical unit?", answer: "93,000,000"...
require_relative 'path' class BFS TOP_VISIT = 5 def initialize(graph, source_node) @graph = graph @source_node = @graph[source_node] @visits = {} @paths_to = {} @graph.nodes.each do |node| @paths_to[node] = [] end @queue = [] find_all_paths end def [](node_name) @pa...
# When running in a production environment, errors get routed to the error.erb view. configure :production do error(400) { erb 'error', layout: false, locals: { code: '400', message: 'Bad Request' } } error(401) { erb 'error', layout: false, locals: { code: '401', message: 'Unauthorized' } } erro...
require 'minitest/autorun' require 'minitest/pride' require './lib/ship' require './lib/cell' require './lib/board' require 'pry' class BoardTest < Minitest::Test def setup @board = Board.new @cruiser = Ship.new("Cruiser", 3) @submarine = Ship.new("Submarine", 2) end def test_board_exist asser...
module Effect class Smite < Effect::ChargeAttack attr_reader :evil_damage attr_reader :demon_damage def initialize(parent, costs = nil, name = nil, damage = 0, damage_type = :none, hit_chance = 0, evil_damage = 0, demon_damage = 0) super parent, costs, name, damage, damage_type, hit_chance @evil_damage ...
# encoding: utf-8 require 'test_helper' module Nls module EndpointInterpret class TestDates < NlsTestCommon def set_now(date) @now = DateTime(date) end def setup super Nls.remove_all_packages Nls.package_update(fixture_parse("package_number_digits.json")) ...
class ShortenedUrl < ApplicationRecord UNIQUE_ID_LENGTH=5 validates :original_url, presence: true, on: :create validates_format_of :original_url, with: /\A(?:(?:http|https):\/\/)?([-a-zA-Z0-9.]{2,256}\.[a-z]{2,4})\b(?:\/[-a-zA-Z0-9@,!:%_\+.~#?&\/\/=]*)?\z/ before_create :generate_short_url before_create :saniti...
class Monster < ApplicationRecord validates_uniqueness_of :name validates_presence_of :name has_and_belongs_to_many :special_abilities has_and_belongs_to_many :actions has_and_belongs_to_many :reactions def special_abilities=(abilities=[]) abilities.each do |ability| ability_record = SpecialAbi...
class AddNickToUsers < ActiveRecord::Migration def self.up add_column :users, :nick, :string add_column :users, :first, :string add_column :users, :last, :string end def self.down remove_column :users, :last remove_column :users, :first remove_column :users, :nick end end
ArtistType = GraphQL::ObjectType.define do name "Artist" field :id, types.ID field :name, types.String field :created_at, types.String field :artist_uri, types.String field :artist_image, types.String end
module BrewSparkling module Action module Install class InstallApp < Base def call logger.start "Installing app" if install_app logger.info "⚡️ #{recipe.name} is installed" else logger.error "🙅 #{recipe.name} install is failed" end ...
class UserRequest < ActiveRecord::Base EMAIL_REGEX= /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\Z/i validates :email, :presence =>true, :length => {:within => 6..50}, :format =>EMAIL_REGEX end
# p046xreadwrite.rb # Abra e leia um arquivo de texto # Note que visto que um bloco é dado, o arquivo será fechado automaticamente begin File.open('p014constructs.rb', 'r') do |f1| while line = f1.gets puts line end end # Cria um novo arquivo e escreve nele File.open('test.rb', 'w') do |f2| #...
require "spec_helper" RSpec.describe "Day 6: Memory Reallocation" do let(:runner) { Runner.new("2017/06") } let(:input) { "0 2 7 0" } describe "Part One" do let(:solution) { runner.execute!(input, part: 1) } it "counts the redistribution cycles before looping" do expect(solution).to eq(5) end...
# frozen_string_literal: true class Customer attr_reader :user_id, :name, :location def initialize(customer_hash) @user_id = customer_hash.fetch('user_id') @name = customer_hash.fetch('name') @location = Location.new(customer_hash.fetch('latitude'), customer_hash.fetch('longitude')) rescue Location:...
source 'http://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails' # Use sqlite3 as the database for Active Record gem 'sqlite3' gem 'pg' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby #Flexible authenticatio...
require 'test_helper' class AgentsSelectionControllerTest < ActionDispatch::IntegrationTest # # List available destinations # test 'Allow entities list available destinations' do sign_in users(:admin) get agents_selection_user_agent_url(users(:admin), agents(:weather), from: 'interpretations', curren...
module Api class UsersController < ApplicationController skip_before_action :user_authenticate , only: [:create, :login, :delete_user] def create user = User.new(user_params) user.save! render json:{ message: "success!!" } rescue => e render json:{ message: "failed save" } end...
# Problem 275: Balanced Sculptures # http://projecteuler.net/problem=275 # Let us define a balanced sculpture of order n as follows: # A polyomino made up of n+1 tiles known as the blocks (n tiles) and the plinth (remaining tile); # the plinth has its centre at position (x = 0, y = 0); # the blocks have y-coordinates ...
class SendSlackCommentService def self.call(comment_id) self.new(comment_id).call end def initialize(comment_id) @comment_id = comment_id end def call github_comment = GithubComment.find_by(id: @comment_id) pull_request = PullRequest.where("lower(url) = ?", github_comment.try(:pr_url).downca...
class Project < ApplicationRecord has_many :tracts has_many :keydates has_many :google_files validates :name, numericality: { only_integer: true, :greater_than_or_equal_to => 0 }, :presence => true rails_admin do configure :name do label 'OPW #' end end end
require 'rails_helper' describe Profile do it { expect(subject).to belong_to(:user) } it { expect(subject).to validate_presence_of(:user_id) } it { expect(subject).to validate_presence_of(:nickname) } it { expect(subject).to validate_uniqueness_of(:nickname) } describe '::by_nickname' do let(:profile) ...
module Thumblemonks module Oughta module MacroMacros module ClassMethods # Defines a macro for use in a TestCase or Context with the given name and block. # For example, this defines a macro called :should_be_cool # # macro :should_be_cool do # ...
class WelcomeController < ApplicationController def index @topics = Topic.all @likes = Like.all end end
class AddContent3ToMomstories < ActiveRecord::Migration def change add_column :momstories, :content3, :text end end
source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.0.0', '>= 5.0.0.1' gem 'puma', '~> 3.0' gem 'bcrypt', '~> 3.1.7' gem 'jwt' gem 'twilio-ruby' gem 'simple_command' gem 'active_hash_relation', github: 'kollegorna/active_hash_relation' gem 'pundit', '~> 0.3...
Sequel.migration do up do alter_table :urls do set_column_allow_null(:title, true) end end down do alter_table :urls do set_column_allow_null(:title, false) end end end
class Board < ActiveRecord::Base has_many :links def self.select_boards all.map { |category| [board.category, board.id] } end end
require 'rails_helper' RSpec.describe "Requests", type: :system do describe "request/new" do let!(:user) { create :user } let!(:request) { create :request } before do log_in_as user visit new_request_path end it "request success" do fill_in "request-form-area", with: request.c...
require "cgi" require "nokogiri" module Conduit::Driver::Sureaddress module Parser # Base XML parser for Sureaddress responses. # Includes parsing of errors and invalid # content. Subclasses must address # parsing of specific attributes. class Base < Conduit::Core::Parser attr_accessor :xm...
LINES = INPUT.split("\n").map(&:chars) PAIRINGS = {"(" => ")", "[" => "]", "{" => "}", "<" => ">"}.freeze ERROR_SCORES = {")" => 3, "]" => 57, "}" => 1197, ">" => 25_137}.freeze AutocompleteError = Class.new(RuntimeError) def autocomplete(line) unresolved = [] line.each do |char| case char when *PAIRING...