samedi 27 juin 2015

Using arrays in regular expressions?

Does anyone know if there is a way to use an array in a regular expression? suppose I want to find out if somefile.txt contains one of an array's elements. Obviously the code below doesn't work, but is there something similar that does work?

array = [thing1 thing2 thing3]
file = File.open("somefile.txt")

file.each_do |line|
if /array/.match(line)
puts line
end

Basically I've got a file that contains a list of words that I need to use as search terms in another large file, and I'd like to avoid something like this:

($somefile =~ /(thing1|thing2|thing3)/)

How do I test fulltext fields using sunspot_matchers in rspec?

My search controller does this:

search = Sunspot.search(Item) do
  fulltext params[:q] do
    fields(:foo, :bar, :bletch)
  end
end

And in my rspec controller test I have the following:

get :show, :q => q

expect(Sunspot.session).to have_search_params(:fulltext, q, proc do
  fields(:foo, :bar, :bletch)
end)

Side note: when I tried using a block instead of a proc, the block was never executed:

have_search_params(:fulltext, q) do
  # This block was never executed
end

My support/sunspot.rb contains only the following:

Sunspot.session = SunspotMatchers::SunspotSessionSpy.new(Sunspot.session)

When I run the test, I get the following error:

  1) SearchController GET search when a user runs a search performs a fulltext search on the right fields
     Failure/Error: fields(:foo, :bar, :bletch)
     NoMethodError:
       undefined method `fields' for #<Sunspot::DSL::Search:0x007fa0f0da0168>
     # ./spec/controllers/search_controller_spec.rb:28:in `block (5 levels) in <top (required)>'
     # ./spec/controllers/search_controller_spec.rb:27:in `block (4 levels) in <top (required)>'

What's the right way to test that my controller is supplying the correct params when doing a fulltext search? Google yields no relevant results when querying this problem.

How to get stand-alone ohai to recognize custom plugin_path?

I have chef configured to add "/etc/chef/ohai_plugins" to Ohai::Config[:plugin_path]. However, the Chef documentation says:

"The Ohai executable ignores settings in the client.rb file when Ohai is run independently of the chef-client."

So, how can I get a stand-alone run of ohai to load and use the plugins in that custom path?

(Background: I have a custom plugin that reports some information that we keep track of for a fleet of servers, like whether a server has been patched for heartbleed or shellshock. I want to be able to run "ssh somehost ohai", parse the JSON that gets sent back, and extract the information I need.)

Thanks.

Finding smallest prime factor

I am trying to create a function that returns the smallest prime factor of a given number:

require 'prime'

def findSmallestPrimeFactor(number)
  return 2 if number.even?
  return number if Prime.prime? number
  arrayOfFactors = (1..number).collect { |n| n if number % n == 0 }.compact
  arrayOfFactors.each { |n| arrayOfFactors.pop(n) unless Prime.prime? n }
  return arrayOfFactors[0]
end

findSmallestPrimeFactor(13333) returns 1, which should not be happening since 1 should be removed from arrayOfFactors during line 7, as Prime.prime? 1 returns false

It sometimes returns nothing:

puts findSmallestPrimeFactor(13335) # => returns empty line

This issue only occurs when working with a number that is not even and is not prime, i.e lines 4 and 5 are ignored.

Also, when this is finished I will be passing some very large numbers through it. Is there any shorter or more efficient way to do lines 6-8 for larger numbers?

What's the difference between a secure compare and a simple ==(=)

Github's securing webhooks page says:

Using a plain == operator is not advised. A method like secure_compare performs a “constant time” string comparison, which renders it safe from certain timing attacks against regular equality operators.

I use bcrypt.compare('string', 'computed hash') when comparing passwords.

What makes this a "secure compare" and can I do this using the standard crypto library in Node?

Failure/Error: visit movie_url(movie) ActionView::Template::Error: wrong number of arguments (3 for 0..1)

This question sounds very similar to those that have already been asked and answered thought I can't seem to figure it out.

I have the following error message that makes my spec test fail.

Failures:

  1) Navigating movies allows navigation from the detail page to the listing page
     Failure/Error: visit movie_url(movie)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # ./app/views/movies/show.html.erb:24:in `_app_views_movies_show_html_erb__1138068182152565203_70152862507580'
     # ./spec/navigate_movies_spec.rb:12:in `block (2 levels) in <top (required)>'

Finished in 0.20747 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/navigate_movies_spec.rb:5 # Navigating movies allows navigation from the detail page to the listing page

Randomized with seed 14064

My actual spec test looks like this:

require 'spec_helper'
include Rails.application.routes.url_helpers

  describe "Navigating movies" do
    it "allows navigation from the detail page to the listing page" do
    ...
    visit movie_url(movie)

    click_link "All Movies"

    expect(current_path).to eq(movies_path)
  end
end

My show page:

<article>
  <p>
     <%= link_to "All Movies", movies_path %>
  </p>
</article>

Edited:

rake routes
Prefix Verb URI Pattern           Controller#Action
movies GET  /movies(.:format)     movies#index
 movie GET  /movies/:id(.:format) movies#show

Mobile app development using ruby

[I]s there any way to develop android apps using ruby? [I]f any[,] please enlighten me on this,[ ]and please let me know the frameworks used.

Run/Install ruby gem from io.js with child_process

AIM: Create a desktop app(GUI) with Electron(Atom Shell), that runs a gem's commands from io.js.

1. The problem is that I want to know which is the best way to handle the commands call to the gem inside the system.

2. If the gem is not installed inside the system the desktop app is worthless. Which is the best way to handle this dependency?

EXAMPLE CODE THAT I'VE SORTED OUT

var spawn = require("child_process").spawn;
var jk = spawn('jekyll', ['serve']);

jk.stdout.on('data', function(data){
  console.log(data.toString('utf8')); // WRITE IN THE CONSOLE GEM OUTPUT
});

Is that code a good way to execute the commands?.

My ideal scenario is "As a user I want to press a button that compile the site" -> On click then run the build command of the gem that will be handled by that code possibly.

Rails Form_Tag Ajax Format.js ActionController::UnknownFormat

I have a form_tag for sending an email and I want to use AJAX, so that only the form could update and the rest would look the same.

contact.html.erb

<%= form_tag(site_contact_path, remote: true, class: 'response form-horizontal', authenticity_token: true) do %>
        <h2 class="contact-title">Parašykite mums</h2>
        <div class="form-group">
          <label class="control-label col-sm-4" for="name">Vardas</label>
          <div class="col-sm-8">
            <%= text_field_tag 'name', nil, placeholder: 'Įveskite vardą', class: 'form-control', autocomplete: 'on' %>
          </div>
        </div>

        <div class="form-group">
          <label class="control-label col-sm-4" for="email">El. paštas</label>
          <div class="col-sm-8">
            <%= text_field_tag 'email', nil, placeholder: 'Įveskite el.paštą', class: 'form-control', autocomplete: 'on' %>
          </div>
        </div>

        <div class="form-group">
          <label class="control-label col-sm-4" for="comment">Komentarai</label>
          <div class="col-sm-8">
            <%= text_area_tag 'comment', nil, placeholder: 'Jūsų komentaras', class: 'form-control', autocomplete: 'on', rows: '6' %>
          </div>
        </div>
        <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
        <div class="button-holder"> 
            <%= submit_tag 'Siųsti', class: 'submit' %>
        </div>
        <div class="hidden">
            <p>Ačiū! (Mes pasistenksime atsakyti Jums, kuo greičiau)</p>
        </div>
    <% end %>

routes.rb

post '/contact' => 'site#contact_send_email'

site_controller.rb

def contact_send_email
@name = params[:name]
@email = params[:email]
@comment = params[:comment]

ContactMailer.send_message(@name, @email, @comment).deliver

respond_to do |format|
    format.js
end
end

contact_send_email.js.erb

$('.form-group').hide();
$('.button-holder').hide();
$('.hidden').show();

log

 ActionController::UnknownFormat (ActionController::UnknownFormat):  app/controllers/site_controller.rb:24:in `contact_send_email'

When I press the submit button, the email is send but it seems contact_send_email action can't find contact_send_email.js.erb for some reason or doesn't understand format.js I've tried searching for similar problem on StackOverflow but the solutions didn't seem to make any effect.

grouped_collection_select and has_many, through

I'm trying to setup a form for tasks where the user selects a game and the achievements that belong to it, following Ryan Bates' tutorial. The only difference between that tutorial and what I'm working on is that I have a has_many through association in my Task model.

In the form I seem to get this error on the line for my grouped_collection_select:

undefined method 'achievement_id' for #<Task:0x007fe4da7e8cd8>

Models

class Game < ActiveRecord::Base
  has_many :achievements
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :game
  has_many :achievements, through: :game
end

class Achievement < ActiveRecord::Base
  belong_to :game
end

Tasks Form

<%= form_for(@task) do |f| %>
  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :game_id %><br>
    <%= f.collection_select :game_id, Game.order(:title), :id, :title, include_blank: true %>
  </div>
  <div class="field">
    <%= f.label :achievement_ids %><br>
    <%= f.grouped_collection_select :achievement_id, Achievement.order(:title), :achievement, :title, :id, :title, include_blank: true, multiple: true %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

How to get the full street address via the geocoder gem?

I am using geocoder with Google to validate addresses and give me back the correct values if they are munged slightly as well as to acquire latitude and longitude. I think I may be a bit off in my implementation here because it just feels so clunky and also I'm finding that some of the addresses are missing the street number.

I am starting off with the following code:

result = Geocoder.search(full_address_to_verify)
if result != []
  street_address = result[0].address_components[1]["long_name"]
  city = result[0].address_components[2]["long_name"]
  state = result[0].address_components[5]["long_name"]
  zip = result[0].address_components[7]["long_name"]
end  

I have found that sometimes I get multiple results, and so I am going with the first one ([0] above). Further, I have found some queerness in that most of the time result[0].address_components[1] contains the full address, including the street_number, but once in a while it does not and I have to then add result[0].address_components[0]. I have yet to figure out a rhyme or reason to this.

Ultimately my goal here is to retrieve the USA street number + street, city, state and zip code fields into separate variables.

So my question is, is there a better way to retrieve the address so that the street number is always associated properly with the route?

From the documentation I'm not really seeing any clean methods that would just simply give me the desired address fields without pulling the data out of the individual fields from the request reply...

Why does form_for(@object) do |f| work in the _form.html.erb but not in the index.html.erb

Ok, So i'm trying to place the form found in the _form.html.erb in my index.html.erb of my ruby project crashes with the error

"First argument in form cannot contain nil or be empty"

<%= form_for(@customer) do |f| %>

I know that changing the @customer to Customer.new could fix this but I would like to know why this isn't necessary in one file and it is in another

Why is this happening and how do I make a form that will update the sqlite db on the index page.

Spree commerce admin to a subdomain

In Spree Commerce how can I set admin link to a subdomain.

the existing is http://ift.tt/1Mc6bt1 to access the admin

I want to do is http://ift.tt/1BXZnxr to access the admin page

Learning Ruby with a Projected Oriented Approach

Whats the best online resource to learn ruby? I'm looking to learn with a more project oriented approach. I wish there was a color by numbers so to speak for ruby projects that I can learn from.

Rails Associations - user_id states nil Rails 4

I am completely unsure where i am going wrong and it surprises me that i can not figure it out, so any advise would be much appreciated.

  1. i have 2 models userr(recruiters) & feedbackr(recruiters feedback)
  2. [userr model] userr has_many :feedbackr
  3. [feedbackr model] belongs_to :userr
  4. [schema] i have added userr_id column to the table feedbackrs
  5. [feedbackrs_controller] i have added :userr_id to the feedbackr_params

the problem is, when i create a feedback comment as a recruiter & go into my console and type Feebackr.find(4) (the last created feedback) the userr_id shows nil - it is suppose to display the id of the userr(recruiter) that created a feedback - i am unsure why it is displaying nil as my associations all seem right -

any advise would be much appreciated - i have my files below -

console

2.1.2 :055 > ap Feedbackr.find(4)
  Feedbackr Load (0.3ms)  SELECT  "feedbackrs".* FROM "feedbackrs"  WHERE "feedbackrs"."id" = ? LIMIT 1  [["id", 4]]
#<Feedbackr:0x007fd89136e018> {
                       :id => 4,
                    :email => "richill@gmail.com",
               :created_at => Sun, 28 Jun 2015 00:29:52 UTC +00:00,
               :updated_at => Sun, 28 Jun 2015 00:29:52 UTC +00:00,
    :category_feedbackr_id => 6,
                  :content => "feedback1",
                 :userr_id => nil
}
 => nil 
2.1.2 :056 > 

schema

ActiveRecord::Schema.define(version: 20150627235330) do

  create_table "feedbackrs", force: true do |t|
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "category_feedbackr_id"
    t.text     "content"
    t.integer  "userr_id"
  end

  create_table "userrs", force: true do |t|
    t.string   "email",                    default: "", null: false
    t.string   "encrypted_password",       default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",            default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
  end

  add_index "userrs", ["confirmation_token"], name: "index_userrs_on_confirmation_token", unique: true
  add_index "userrs", ["email"], name: "index_userrs_on_email", unique: true
  add_index "userrs", ["reset_password_token"], name: "index_userrs_on_reset_password_token", unique: true

end

feedbackr.rb

class Feedbackr < ActiveRecord::Base
  belongs_to :userr
end

userr.rb

class Userr < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  has_many :feedback's
end

feedbackr_controller.rb

class FeedbackrsController < ApplicationController
  respond_to :html, :xml, :json
  before_action :set_feedbackr, only: [:show, :edit, :update, :destroy]

  def index
    @feedbackrs = Feedbackr.all.order("created_at DESC")
    respond_with(@feedbackrs)
  end

  def show
    respond_with(@feedbackr)
  end

  def new
    @feedbackr = Feedbackr.new
    respond_with(@feedbackr)
  end

  def edit
  end

  def create
    @feedbackr = Feedbackr.new(feedbackr_params)
    respond_to do |format|
      if @feedbackr.save
        format.html { redirect_to dashboard_path, :notice => 'Thank you for your feedback' }
        format.xml  { render :xml => @feedbackr, :status => :created, :location => [@feedbackr] }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @feedbackr.errors, :status => :unprocessable_entity }
      end  
    end
  end

  def update
    ...
  end

  def destroy
    ...
  end

  private
    def set_feedbackr
      @feedbackr = Feedbackr.find(params[:id])
    end

    def feedbackr_params
      params.require(:feedbackr).permit(:email, :category_feedbackr_id, :content, :userr_id)
    end
end

views/feedbackrs/_form.html.erb

<%= simple_form_for(@feedbackr) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input_field :email, label: 'email address', value: current_userr.email %>
    <%= f.association :category_feedbackr, as: :radio_buttons, label: 'How likely are you to recommend us?' %>
    <%= f.input :content, label: 'What is the primary reason for your score?'%>
  </div>

  <div class="form-actions">
    <%= f.button :submit, 'Provide Feedback' %>
  </div>
<% end %>
<div><%= render 'shared/footer' %></div>

I can't remove cmd association extension in windows 7

I've tried almost everything and nothing works

I clicked on make defauls association to win console cmd over a .rb file and now it is impossible to change.

what can i do to fix it ?

one image have more value than 1000 words

Pry not finding installed gems (ruby 2.2.0, rvm)

tl;dr

Pry can't find several of my installed gems because the gems found by Gem::Specification are different than the gems found by gem list --local. The ruby versions are the same, and the path to the found and not-found gems seems to be the same.

I'm thinking that I must have some mix up with paths or ruby versions, but I can't find the culprit. Any ideas of how to untangle this?


Details

I'm running ruby 2.2.0 using rvm on OS X Yosemite, and I'm having an issue getting pry to find several of my installed gems (in particular, pry-doc).

Here are my versions:

lee$ ruby -v 
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]

lee$ pry -v
Pry version 0.10.1 on Ruby 2.2.0

lee$ gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.4.6
  - RUBY VERSION: 2.2.0 (2014-12-25 patchlevel 0) [x86_64-darwin14]
  - INSTALLATION DIRECTORY: /usr/local/rvm/gems/ruby-2.2.0
  - RUBY EXECUTABLE: /usr/local/rvm/rubies/ruby-2.2.0/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/rvm/gems/ruby-2.2.0/bin
  - SPEC CACHE DIRECTORY: /Users/lee/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-14
  - GEM PATHS:
     - /usr/local/rvm/gems/ruby-2.2.0
     - /usr/local/rvm/gems/ruby-2.2.0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "--omg"
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /usr/local/rvm/gems/ruby-2.2.0/bin
     - /usr/local/rvm/gems/ruby-2.2.0@global/bin
     - /usr/local/rvm/rubies/ruby-2.2.0/bin
     - /usr/local/rvm/bin
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /usr/local/git/bin
     - /opt/sm/bin
     - /opt/sm/pkg/active/bin
     - /opt/sm/pkg/active/sbin
     - /opt/sm/bin
     - /opt/sm/pkg/active/bin
     - /opt/sm/pkg/active/sbin

Listing gems via the command line returns what I expect:

lee$ gem list --local | grep 'pry'
pry (0.10.1)
pry-doc (0.8.0)
pry-git (0.2.3)
pry-nav (0.2.4)
pry-rails (0.3.4)

And the paths for both pry and bash seem to be the same

lee$ gem which pry
/usr/local/rvm/gems/ruby-2.2.0/gems/pry-0.10.1/lib/pry.rb

lee$ gem which pry-doc
/usr/local/rvm/gems/ruby-2.2.0/gems/pry-doc-0.8.0/lib/pry-doc.rb

pry(main)> $ pry
From: /usr/local/rvm/gems/ruby-2.2.0/gems/pry-0.10.1/lib/pry/core_extensions.rb @ line 41:
... 

However, in pry, the gems available to be installed are controlled by Gem::Specification from the rubygems library. Running the following:

# I know this method is a mess, but it does the job
def prys
  Gem::Specification.sort_by{ |g| [g.name.downcase, g.version] }
    .select { |g| g.name =~ /pry/ }
    .group_by{ |g| g.name }
    .map { |name, versions| 
      "#{name} (#{versions.map { |v| v.version.to_s }.join(', ') })" 
    }
end

prys

returns:

=> ["pry (0.10.1)", "pry-rails (0.3.4)"]


I've tried uninstalling and reinstalling as well as hunting around for another copy of the found gems, but no luck. I can't figure out the pattern for what's being returned either.

Any ideas of what to try next?

How to generate 2D array from a set of string in rails?

I need to generate 2D array in rails from a set of given strings. For example:

days =[ "Monday",
     "Tuesday",
     "Wednesday",
  ]

Now I want to create a 2D array and the data in this array will be fill by from days string in random manner.

Example:

[monday, tuesday, wednesday],
[tuesday, wednesday, monday]
...

and so on depends on given dimensions

How to do it?

Foreman start multiple processes?

I have three processes defined in my Procfile. Sometimes, I only want to run two of them. Is there a command for that?

$ foreman start process_1 process_2
ERROR: "foreman start" was called with arguments ["process_1", "process_2"]
Usage: "foreman start [PROCESS]"

More ruby-like way of writing simple ActiveRecord code

Here is some fairly standard Ruby on Rails 4 ActiveRecord code:

  def hide(user)    
    self.hidden = true
    self.hidden_on = DateTime.now
    self.hidden_by = user.id
  end

  def unhide
    self.hidden = false
    self.hidden_on = nil
    self.hidden_by = nil
  end

  def lock(user)
    self.locked = true
    self.locked_on = DateTime.now
    self.locked_by = user.id
  end

  def unlock
    self.locked = false
    self.locked_on = nil
    self.locked_by = nil
  end

  # In effect this is a soft delete
  def take_offline(user)
    hide(user)
    lock(user)
  end

The code is easy to understand and doesn't try to be clever. However it feels verbose. What would be a more succinct or canonical way of specifying this code/behaviour?

Database migration stops halfway through

I've had issues trying to use PostgreSQL so changed my application to use MYSQL.

But, when I run rake db:migrate I get the following message before the migration stops:

-- PostgreSQL database dump complete

However when I run rake db:seed, I get told that I still have 303 migrations left. How can I complete this migration?

How to make multi-line string literals in Ruby without using HERE-DOCUMENT syntax?

Summary of the problem

I'd like to try Ruby for something I did in Python. In Python it has the r""" syntax to support raw strings, which is nice as it allows one to have raw strings in-line with the code and to concatenate them in more natural way and with no special indentation needed. In Ruby, when using raw strings, one has to use <<'EOT' followed by EOT in separate line which breaks the code layout.

You might ask, why not then use Ruby's %q{}? Well, because %q{} has limitations compared to Python's r""" as it does not escape multiple \\\ and only handles single \.

I am generating Latex code on the fly and write to a file, which later is compiled with pdflatex. The Latex code contain things like \\\ in many places. If I use Ruby's %q{} syntax, then it will not work. So I have to use Ruby's <<'EOT' but I do not want to do this, as it makes the code harder to read in the Ruby source file due to having to break it for indentation to make EOT happy.

I am asking if there is a way to make syntax similar to %q{}, or some function that take string and return same result as if one used EOT, that handles raw strings without the limitation of EOT.

I do not need interpolation. So single quoted strings only. No double quoted. double quotes causes interpolation, which I do not want.

Small working examples to illustrate

Here is a small example in Python, and then I show what I have to do in Ruby to generate the same output.

my_file = open("py_latex.tex", 'w')
x = r"""\\\hline is a raw string"""+r""" another one \\\hline and so on"""
my_file.write(x)

When I open the Latex text file written to in the above, I see the correct result

Mathematica graphics

Now to do the same thing in Ruby. I can't write the following (even though I'd like to)

file = File.open('rb_latex.tex','w')
x=%q{\\\hline is a raw string}+%q{ another one \\\hline and so on}
file.write(x)

The above ofcourse is not what I want. When it is written to latex file, it shows up as

Mathematica graphics

Using EOT works, as follows

file = File.open('rb_latex.tex','w')
x=<<-'EOT1'+<<-'EOT2'
\\\hline is a raw string
EOT1
 another one \\\hline and so on
EOT2
file.write(x)

And the file now is

Mathematica graphics

ps. it makes the second string on new line, this is a side-issue for me now, and will try to find solution for this after I solve the main problem at hand.

Short summary of the question

How to make %q{} like syntax for Ruby that works similar to Python r""" ?

If someone wants to try the above code in Ruby, make sure there is no space after EOT. I also include below the full source code.

Python full source

import os
os.chdir(" direct to change to here ")    
my_file = open("py_latex.tex", 'w')
x = r"""\\\hline is a raw string"""+r""" another one \\\hline and so on"""
my_file.write(x)
my_file.close()

Ruby source code

#!/usr/local/bin/ruby -w
Dir.chdir("/home/....")
file = File.open('rb_latex.tex','w')
#x=%q{\\\hline is a raw string}+%q{ another one \\\hline and so on}
x=<<-'EOT1'+<<-'EOT2'
\\\hline is a raw string
EOT1
 another one \\\hline and so on
EOT2
file.write(x)
file.close

Rails 4 create model with nested attributes has_many

I have a many to many relationship with DoctorProfile and Insurance. I'd like to create these associations off of a form from a client side app. I'm sending back an array of doctor_insurances_ids and trying to create the association in one line. Is it possible to send back an array of doctor_insurances ids? If so what's the proper way to name it for mass assignment in the params?

The error I'm getting with the following code is

ActiveRecord::UnknownAttributeError: unknown attribute 'doctor_insurances_ids' for DoctorProfile.

class DoctorProfile
  has_many :doctor_insurances
  accepts_nested_attributes_for :doctor_insurances # not sure if needed

class Insurance < ActiveRecord::Base
  has_many :doctor_insurances

class DoctorInsurance < ActiveRecord::Base
  # only fields are `doctor_profile_id` and `insurance_id`
  belongs_to :doctor_profile
  belongs_to :insurance

def create
  params = {"first_name"=>"steve",
 "last_name"=>"johanson",
 "email"=>"steve@ymail.com",
 "password_digest"=>"password",
 "specialty_id"=>262,
 "doctor_insurances_ids"=>["44", "47"]}

  DoctorProfile.create(params)

end

Ruby on Rails Solving a No method Error

I'm currently going through Hartl's Ruby on Rails tutorial and I've come to a roadbloack with a failing test that I don't know how to get to pass. All of the previous tests through chapter 11 have ran correctly so I was hoping some one could help me interpret the errors.

Running:

bundle exec rake test

Gives me this

45 runs, 0 assertions, 0 failures, 45 errors, 0 skips

The first six errors are similar to this:

1) Error:
MicropostTest#test_should_be_valid:
ActiveRecord::Fixture::FormatError: ActiveRecord::Fixture::FormatError

And the rest of the errors follow this pattern:

7) Error:
UsersEditTest#test_unsuccessful_edit:
ActiveRecord::Fixture::FormatError: ActiveRecord::Fixture::FormatError


Error:
UsersEditTest#test_unsuccessful_edit:
NoMethodError: undefined method `each' for nil:NilClass

I'm not sure what an undefined method for a nil class would mean. If I need to post any more of my code/errors please let me know. Any help is appreciated. Thanks!

Updating message counter on private_pub publish

I am creating a chat module for my application and using private_pub for sending and receiving messages. I want to update the unread message counter on receiver's as soon as receiver gets the message.

Each page is subscribed to a channel where message gets published, so that every time I get the message, the counter on the page gets updated.

Following js file is executed when a new message is created.

<% publish_to conversation_messages_path(@conversation.id) do %>
    $("#messages").append("<%= escape_javascript render(:partial => 'message', :locals => { :message => @message })%>");
    $("#unread_messages_count").text("<%= current_user.received_messages.unread.size %>");
<% end %>
// @conversation.messages.where(:read => 0)
$("#newMessageForm")[0].reset();
$("#messages").scrollTop($("#messages")[0].scrollHeight);

The page gets updated but current_user.received_messages.unread.size gives me the sender's unread count, why is this so?

This means the current_user should be different for every other page who has subscribe_to that URL. As of now current_user is the one who publish_to that URL which results in the same value of unread messages count for every different client.

One possible solution is to send the user id of the one who is currently logged in while we subscribe_to a URL and in publish_to use that to get the unread messages count but the problem is I don't know how to send data while subscribing and using it in publish.

How to load a component file just once in VoltRb

I have a component that I only want to load once in my Volt project. Loading more than once will cause problems, similarly to loading the OpalRb library more than once. To clarify, I am loading this component in a view file, and it keeps getting loaded because the line loading the component keeps getting called every time the page gets hit:

{{ if condition }}
{{   require 'component/lib/file' # this line keeps getting called }}
{{ end }}

How do I set up my code so that I can load a component only once?

Static lookup table but only ouput what's changed

This is an extension/enhancement of a question I asked a while back and it provides all the code & context hopefully.

I have the lookup table in the question linked above running nicely - what I'd like to do now is have a look at how I can optimise my code so that only the bits that have changed are output rather than all 8 bits at a time.

Should I be looking at holding the state of a bit in a Db? (If so I already have them in MongoDb) or something more simple?

Any advise, pointers or examples would be great.

css media queries replace map with embed image

I'm trying to replace a gmap that I have on my index page with an embedded image version for mobile. The map looks okay on desktop but when I view it on mobile it is too long and scrolling to the end of the page is challenging due to the gmap. I've set "scrollwheel: false" on the JS which fixed this for desktop but on mobile still does not work. I've also placed the map width to 90% but the map still looks to large on mobile. So I've decided to replace the map with an embedded image version of it once the screen size goes under 767px. The only thing is that I'm not sure how to go about swapping the two (gmap to image). Any advise would be greatly appreciated.

Some details about the page, it is being displayed using the RoR's "render".

index.html:

<div id="map" class="google-maps">
     <%= render "gmap" %>
</div>

_gmap.html:

<script type="text/javascript">
    handler = Gmaps.build('Google');
    handler.buildMap({
       provider: {
          scrollwheel: false,
          mapTypeId: google.maps.MapTypeId.HYBRID,
          maxZoom: 64
       },
       internal: {
          id: 'map'
       }
    }, function() {
       markers = handler.addMarkers(<%=raw@hash.to_json%>);
       handler.bounds.extendWith(markers);
       handler.fitMapToBounds()
    });
    handler
</script>

gmap.css

.google-maps {  
    width: 90%; 
    height: 100%; 
    margin: 0 auto;
    position: absolute;
    top:0;
    z-index:1;
}

Filter ActiveAdmin with Postgresql json column on specific json keys

I have a Deal model that features a json column called deal_info. It's actually an array of JSONs.

I'm using active admin.

For example :

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

As first step now I would like to have a filter that would enable me to filter the deals based on the fact that deal_info json column includes at least one time the modal_id in one of its included json.

It would enable me in a select dropdown to choose for example modal_id = 6 and would filter the list of Deals to only show deal 1 (see example above).

One of the further challenge is that I need to be able to remove duplicates on the select dropdown in order not to have multiple times the same id: here for example i can't have select = [4,6,9,10,11,11]...each modal_id can only appear once.

I only found this but it did not work for me.

My current Active Admin Code

ActiveAdmin.register Deal do
  filter :modal_id,
  as: :select 
  collection: deal_info.all.to_a.map ???? 
end

What does the single period in `require "./file_name.rb"` do?

In lines like:

require "./hello.rb"

What does the single period do? I know that using 2 periods is going back a directory from current location.

Also, is there a difference in the following:

require_relative "../file.rb"

require "../file.rb"

Sort two array of hashes by the same criteria on Ruby

I am working on Ruby with two arrays of hashes like these:

a = [{'name'=> 'Ana', 'age'=> 42 },
     {'name'=> 'Oscar', 'age'=> 22 },
     {'name'=> 'Dany', 'age'=> 12 }]

b = [{'name'=> 'Dany', 'country'=> 'Canada' },
     {'name'=> 'Oscar', 'country'=> 'Peru'},
     {'name'=> 'Ana', 'country'=>'France'}]

I am sorting them like this:

a.sort_by!{|c| c['name']}
b.sort_by!{|c| c['name']}

and it works, but since I doing the same on both arrays, I would like doing the same but in one line; I mean, sort the two arrays at once.

How can I do it?

Ruby csv - delete row if column is empty

Trying to delete rows from the csv file here with Ruby without success.

How can I tell that all rows, where column "newprice" is empty, should be deleted?

require 'csv' 
guests = CSV.table('new.csv', headers:true)

guests.each do |guest_row|
  p guests.to_s 
end

price = CSV.foreach('new.csv', headers:true) do |row|
  puts row['newprice'] 
end 

guests.delete_if('newprice' = '')

File.open('new_output.csv', 'w') do |f|
  f.write(guests.to_csv)
end

Thanks!

How to show error message on rails views?

I am newbie in rails and want to apply validation on form fields.

myviewsnew.html.erb

<%= form_for :simulation, url: simulations_path do |f|  %>

<div class="form-group">
  <%= f.label :Row %>
  <div class="row">
    <div class="col-sm-2">
      <%= f.text_field :row, class: 'form-control' %>
    </div>
  </div>
</div>
.....

Simulation.rb

class Simulation < ActiveRecord::Base
 belongs_to :user
 validates :row, :inclusion => { :in => 1..25, :message => 'The row must be between 1 and 25' }
end

I want to check the integer range of row field in model class and return the error message if it's not in the range. I can check the range from above code but not able to return the error message

Thanks in advance

rake aborted! LoadError: cannot load such file

I am completely newbie to this rails frame work and learning via online tutorials. I am in the process of developing a simple application with the help of rails(rails+Mysql).

Currently i am facing an issue with "rake" command.

When i tried to "rake db:schema:dump" the following errors are coming.Pls suggest me some thing.

Thanks in advance.

harsha@Trebuchet:~/simp_cms$ rake db:schema:dump --trace
rake aborted!
LoadError: cannot load such file -- bundler/setup
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/simp_cms/config/boot.rb:3:in `<top (required)>'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/simp_cms/config/application.rb:1:in `<top (required)>'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/simp_cms/Rakefile:4:in `<top (required)>'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:689:in `raw_load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:94:in `block in load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:93:in `load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:77:in `block in run'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:75:in `run'
/home/harsha/.rbenv/versions/2.2.2/bin/rake:33:in `<main>'

harsha@Trebuchet:~/simp_cms$ bundle exec rake db:schema:dump --trace
/var/lib/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/shared_helpers.rb:78: warning: Insecure world writable dir /usr in PATH, mode 040777
Could not find debugger-1.6.8 in any of the sources
Run `bundle install` to install missing gems.

harsha@Trebuchet:~/simp_cms$ gem install debugger -v 1.6.8
Building native extensions.  This could take a while...
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/ext/builder.rb:73: warning: Insecure world writable dir /usr in PATH, mode 040777
ERROR:  Error installing debugger:
    ERROR: Failed to build gem native extension.

    /home/harsha/.rbenv/versions/2.2.2/bin/ruby -r ./siteconf20150628-11403-1nydzd5.rb extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

My Ruby version, rails version and gem list

harsha@Trebuchet:~$ rails -v
Rails 4.2.2
harsha@Trebuchet:~$ rails -v
Rails 4.2.2
harsha@Trebuchet:~$ gem list

*** LOCAL GEMS ***

actionmailer (4.2.2)
actionpack (4.2.2)
actionview (4.2.2)
activejob (4.2.2)
activemodel (4.2.2)
activerecord (4.2.2)
activesupport (4.2.2)
arel (6.0.0)
bigdecimal (1.2.7, 1.2.6)
binding_of_caller (0.7.2)
builder (3.2.2)
columnize (0.9.0)
debug_inspector (0.0.2)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.3.8)
erubis (2.7.0)
globalid (0.3.5)
i18n (0.7.0)
io-console (0.4.3)
json (1.8.3, 1.8.1)
loofah (2.0.2)
mail (2.6.3)
mime-types (2.6.1)
mini_portile (0.6.2)
minitest (5.7.0, 5.4.3)
mysql2 (0.3.18)
nokogiri (1.6.6.2)
power_assert (0.2.3, 0.2.2)
psych (2.0.13, 2.0.8)
rack (1.6.4)
rack-test (0.6.3)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.6)
rails-html-sanitizer (1.0.2)
rake (10.4.2)
rdoc (4.2.0)
spring (1.3.6)
test-unit (3.1.2, 3.0.8)
thread_safe (0.3.5)
tzinfo (1.2.2) 

Please find my database.yml file

  default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: simp_cms
  password: secretpassword
  socket: /tmp/mysql.sock

development:
  <<: *default
  database: simp_cms_development

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: simp_cms_test 

please feel free to contact me for any more details...

Updating Postgres Database from Ruby file

How do I update a table in a Postgres database from a Ruby file?

I am able to insert, create, and drop a table, but I am unable to update it. I tried to write code that is similar to the one used to insert information into the Postgres database, but it didn't work.

require 'pg'

class PostgresDirect
  # Create the connection instance.
  def connect
    @conn = PG.connect(:dbname => 'postgres')
  end

  # Create our venue table
  def createVenueTable
    @conn.exec("CREATE TABLE venues (venue_number text UNIQUE,...,img_array text[],logo text);")
  end

  # Used to delete the table from the postgres database
  def dropVenueTable
    @conn.exec("DROP TABLE IF EXISTS venues;")
  end

  def prepareInsertVenueStatement
    @conn.prepare("insert_venue", "insert into venues(venue_number,name,...,logo) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25)")
  end

  # Add a venue with the prepared statement.
  def addVenue(venue_number,name,...,logo)

    @conn.exec_prepared("insert_venue", [venue_number,name,...,logo])
  end

  # Code I wrote to try to update postgres table
  def updateImgArray(img,venue)
    @conn.exec("update venues set img_array = array_append(img_array,'#{img}') where venue_number = '#{venue}';")
  end

  def prepareUpdateImgStatement
    @conn.prepare("update_venue", "update venues set img_array = array_append(img_array,'img') where venue_number = 'venue' values ($1,$2)")
  end
end

Getting Rspec error no implicit conversion of Symbol into Integer with Mongoid

I'm tying to test my Rails app with Rspec, but I'm getting a no implicit conversion of Symbol into Integer error without any apparent reason. Based on the traceback I get I think the problem is related to Mongo/Mongoid, however, I can't figure out what it is exactly. The code runs perfectly in production. The error happens only when testing.

Brief look at the model without the other methods:

class Card
  include Mongoid::Document
  field :front, type: String
  field :back, type: String
  field :level, type: Integer, default: 1
  field :review_date, type: DateTime, default: DateTime.now

  embeds_one :card_statistic
  belongs_to :topic
  belongs_to :user

  validates :front, :back, :level, presence: true
  validates :topic, presence: { is: true, message: "must belong to a topic." }
  validates :user, presence: { is: true, message: "must belong to a user." }
  validates :level, numericality: { only_integer: true, greater_than: 0 }
end

One function in the model that triggers the error:

def self.reset(card)
    card.update(level: 1)
end

The test code:

it "puts the given card in level 1" do
    card = create(:card)
    Card.correct card
    card.reload
    Card.correct card
    card.reload
    expect(card.level).to eq(3)
    card.reset
    card.reload
    expect(card.level).to eq(1)
  end

Then, the traceback of the error I get:

1) Card puts the given card in level 1
     Failure/Error: Card.reset card
     TypeError:
       no implicit conversion of Symbol into Integer
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `[]'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `get'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/client.rb:170:in `read_preference'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:318:in `default_read'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:251:in `read'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/iterable.rb:38:in `each'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/query_cache.rb:207:in `each'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:230:in `first'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:230:in `block (2 levels) in first'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:562:in `with_sorting'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:229:in `block in first'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:474:in `try_cache'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:228:in `first'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual.rb:20:in `first'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/builders/referenced/in.rb:20:in `build'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:43:in `create_relation'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:26:in `__build__'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:104:in `block (2 levels) in get_relation'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/threaded/lifecycle.rb:130:in `_loading'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:100:in `block in get_relation'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/threaded/lifecycle.rb:89:in `_building'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:99:in `get_relation'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:187:in `block in getter'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/validatable.rb:79:in `read_attribute_for_validation'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:149:in `block in validate'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:148:in `each'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:148:in `validate'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:450:in `public_send'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:450:in `block in make_lambda'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:189:in `call'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:189:in `block in simple'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `call'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `block in simple'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `call'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `block in simple'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `call'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `_run_callbacks'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:734:in `_run_validate_callbacks'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:395:in `run_validations!'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations/callbacks.rb:113:in `block in run_validations!'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:88:in `call'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:88:in `_run_callbacks'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:734:in `_run_validation_callbacks'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations/callbacks.rb:113:in `run_validations!'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:334:in `valid?'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/validatable.rb:97:in `valid?'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:371:in `invalid?'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:114:in `prepare_update'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:139:in `update_document'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/savable.rb:25:in `save'
     # /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:52:in `update'
     # ./app/models/card.rb:57:in `reset'
     # ./spec/models/card_spec.rb:32:in `block (2 levels) in <top (required)>'

The error is also triggered when testing the controllers. Even doing a get :index throws the error. Thanks in advance for your help.

Editable Webpage Table in Rails

I am trying to make a webpage with a calendar similar to the one in the following link:

 http://cs61a.org/

But I need the page to be editable. I want the user to not only be able to change the contents of the table but also the table structure (Add columns etc). What strategy should I use to tackle this problem?

mapping values through deeply nested associations

A controller extracts data from deeply nested associations where bilancino belongs_to :operativo which in turn belongs_to :cdg as such:

@cdgs = Cdg.order("id ASC").all
@bilancinos = Bilancino.joins(:operativo).order('cdg_id ASC').all

(with a where clause in there).

However when rendering

<% @cdgs.each do |cdg| %>
  <% @cdgs_for_bilancino = @bilancinos.select{ |i| i.operativo.cdg_id == cdg } %>
  <%= @cdgs_for_bilancino.each do |bilancino| %> XX <% end %>
  <%= number_with_precision(@cdgs_for_bilancino.map(&:saldo).sum, :precision => 0, :delimiter => "\u00a0")  %>
<% end %>

is generating an empty array, yet if underneath the following

<% @bilancinos.each do |bilancino| %>
  <%= bilancino.operativo.cdg.conto %> <%= bilancino.saldo %><br />
<% end %>

will render. Thus the expression @bilancinos.select{ |i| i.operativo.cdg_id is missing the nested target somehow.

What is the proper syntax?

Undefined Method for `topic_comment_path`

After I make a comment for any particular post and submit the comment via the Create action to add the comment to the database, I get the error Undefined Method for topic_comment_path. From the error, it looks like the route path is not picking up the local variable comment that I am looping through(@post.comments.each do |comment|) in the show.html.erb file? When I refresh the page, and go back and check the post I see the number of comments has increased due to the post being created. But I can't view the comment after I create it on the Posts#show view. Can anyone offer any assistance?

From Show.html.erb file

<% if @post.comments.present? %> 

<h1>Comments</h1>
<% @post.comments.each do |comment| %>
  <div class="media">
    <div class="media-left">
    <%= image_tag(comment.user.avatar.small.url, class: "media-object") if comment.user.avatar? %>
  </div>
<div class="media-body">
    <small>
      <%= comment.user.name %> commented <%= time_ago_in_words(comment.created_at) %> ago
      <% if policy(comment).destroy? %>
        | <%= link_to "Delete", [@topic, @post, comment], method: :delete %>
      <% end %>
    </small>
    <p><%= comment.body %></p>
</div>
  </div>

<% end %>

From routes.rb file

Rails.application.routes.draw do


get 'comments/create'

devise_for :users


#the resources method lets you restrict which RESTful routes you want
resources :users, only: [:update] #creates new action users#update
resources :topics do
resources :posts, except: [:index] do
  resource :summaries, only: [:create, :show]
  resource :comments, only: [:create, :destroy]
end

end

get 'about' => 'welcome#about'

root to: 'welcome#index'
end

Screenshot of error in browser

topic_post_comment_path error

Comments table schema

create_table "comments", force: :cascade do |t|
t.text     "body"
t.integer  "post_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "user_id"
end

Post controller detail showing the new and create methods for @comment:

class PostsController < ApplicationController


 def show
 @post = Post.find(params[:id])
 @topic = Topic.find(params[:topic_id])

 end

 def new
 @topic = Topic.find(params[:topic_id])
 @post = Post.new
 @comment = Comment.new
 authorize @post 
 authorize @comment 
 end


 def create

 @topic = Topic.find(params[:topic_id])

 @post = current_user.posts.build(post_params)
 @post.topic = @topic
 @comment = Comment.find(params[:id])
 authorize @post 
 authorize @comment

  if @post.save
    flash[:notice] = "Your new post was created and saved."
    redirect_to [@topic, @post] #takes you to the new post you created
  else
    flash[:error] = "There was an error saving the post. Please try again."
    render :new # it grabs the new.html.erb file and pastes it in the view
  end
  end


  def edit
  @topic = Topic.find(params[:topic_id])
  @post = Post.find(params[:id])
  @comment = Comment.find(params[:id])
  authorize @post
  end

Comments Controller

class CommentsController < ApplicationController
 def create
 @topic = Topic.find(params[:topic_id])
 @post = @topic.posts.find(params[:post_id])
 @comment = @post.comments.new(params.require(:comment).permit(:body))
 @comment.user = current_user
 authorize @comment

  @comment.save!#save the code down in the database

 redirect_to [@topic, @post]
 end

def destroy
 @topic = Topic.find(params[:topic_id])
 @post = @topic.posts.find(params[:post_id])
 @comment = @post.comments.find(params[:id])

 authorize @comment
 if @comment.destroy?
  flash[:notice] = "Comment was removed."
  redirect_to [@topic, @post]
 else
  flash[:error] = "Comment couldn't be deleted. Try again."
  redirect_to [@topic, @post]
end
end
end

checkboxs in a table created via form_for

I'm new to RoR so apologies if the answer is super simple. I'm trying to create a table that allows users to select other users that can collaborate on a wiki. The issue I'm having is that no matter which checkbox you select on the table. It only toggles the topmost option.

here is the code in question:

<%= form_for [@wiki, @wiki.collaborators.build] do |f| %>
  <table class="bordered hoverable">
    <tbody>
      <% @users.each do |user| %>
        <tr>
          <td><%= user.name %></td>
          <td class="right-align"><%= f.check_box :user_id %><%= f.label :user_id, "Give Access" %></td>
        </tr>
      <% end %>  
    </tbody>
  </table><br /><br />

the controller values in new

def new
  @wiki = Wiki.find(params[:wiki_id])
  @collaborator = Collaborator.new
  @users = (User.all - [current_user])
end

Postgre error with Rails - I'm running locally but the database won't work properly)

Currently trying to install to run Catarse on my Mac (Yosemite)

When I try and run rake db:create db:migrate db:seed

I get the following message

ActiveRecord::StatementInvalid: PG::DuplicateObject: ERROR:  role "admin" already exists
:     CREATE ROLE admin NOLOGIN;
    -- This script assumes a role postgrest and a role anonymous already created
GRANT usage ON SCHEMA postgrest TO admin;
GRANT usage ON SCHEMA "1" TO admin;
GRANT select, insert ON postgrest.auth TO admin;
GRANT select ON ALL TABLES IN SCHEMA "1" TO admin;
GRANT admin TO postgrest;

I have tried to do the above but to no avail, and now it's saying that I have a duplicate admin role. Can anybody please offer some guidance or assistance?

I've spent most of the day troubleshooting and looking at this over and over again in frustration by doing the following:

Uninstalling catarse Reinstalling and uninstalling postgresql Trying to implement the above 'GRANT' commands

has_many :through broke some code

So i'm relatively new to RoR, and am having some issues in trying to get my code back up and working. So previously I had users, and wikis that users could create. I've set up so that users can subscribe and get premium status to make wikis private. Now I'm in the process of making it so that Premium users can add standard users as collaborators to the wiki. I've decided to got about associating them through has_many :through relationships.

The issue I'm running into so that some of my buttons have started making errors that I don't understand. The one I'm stuck on right now is when showing the page that has a create new wiki button on it.

This is the error I am getting when I added the has_many through: relationship

No route matches {:action=>"new", :controller=>"wikis", :format=>nil, :user_id=>nil} missing required keys: [:user_id]

Here are the models:

collaborator.rb

class Collaborator < ActiveRecord::Base
  belongs_to :wiki
  belongs_to :user
end

user.rb

class User < ActiveRecord::Base

  ...

  has_many :collaborators
  has_many :wikis, :through => :collaborators

end

wiki.rb

class Wiki < ActiveRecord::Base

  belongs_to :user

  has_many :collaborators
  has_many :users, :through => :collaborators

end

The important bits of the wiki_controller.rb

def new
  @user = User.find(params[:user_id])
  @wiki = Wiki.new
  authorize @wiki
end

def create
  @user = current_user
  @wiki = @user.wikis.create(wiki_params)
  authorize @wiki
  if @wiki.save
    flash[:notice] = "Wiki was saved"
    redirect_to @wiki
  else
    flash[:error] = "There was an error saving the Wiki. Please try again"
    render :new
  end
end

And finally the show.html.erb file the button is located in.

<div class="center-align">
  <%= link_to "New Wiki", new_user_wiki_path(@user, @wiki), class: 'btn grey darken-1' %>
</div>

If I'm missing any files or relevant info please let me know. This may be a simple stupid answer but I'm stuck for the life of me.

Thanks in advance.

Edit:

Here is the requested added info, first up the show info in the users_controllers.rb

def show
  @wikis = policy_scope(Wiki)
end

the corresponding policy scope I'm using in the user_policy.rb

class UserPolicy < ApplicationPolicy

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      wikis = []
      all_wikis = scope.all
      all_wikis.each do |wiki|
        if wiki.user == user || wiki.users.include?(user)
          wikis << wiki
        end
      end
    end
    wikis
  end

end

and the route.rb file

Rails.application.routes.draw do

  devise_for :users
  resources :users, only: [:update, :show] do
    resources :wikis, shallow: true
  end

  resources :wikis, only: [:index]
  resources :charges, only: [:new, :create]
  delete '/downgrade', to: 'charges#downgrade'

  authenticated do
    root to: "users#show", as: :authenticated
  end

  root to: 'welcome#index'

end

Hope it helps

Try to get a possibly existing HTML tag

I'm using Nokogiri to parse some HTML:

  doc = Nokogiri::HTML(open(url))
  doc.css('.blockGroup--posts .block')[2..30].each do |article|
    title = article.at('h2').text # or h3, h4
    image = article.at('.section-content img')['src']  # may not exist

The problem is that sometimes the title may appear in h2 or h4 tags, so

title = article.at('h2').text

would report

undefined method `text' for nil:NilClass

The same goes for image. Sometimes there is no image in an article, and it will report an error too.

How can I make Nokogiri get these elements and continue running? Or can I use callbacks if these elements do not exist?

Ruby on rails flash notice error

I have a problem with flash[:notice] = "Message" in Ruby on Rails.

I am trying to create login fault error message. My login fault handling is:

flash[:notice] = "Invalid username/password combination."
redirect_to(:action => 'login')

For the reason I don't know, alert just doesn't show up. I have red tons of possible solutions, but all of them just doesn't work for me. I am using Safari / Google Chrome web browsers.

Rails force instance variable declaration before use on view

Is it possible to force Ruby/Rails to throw an error when printing/using instance variables on a view that haven't been defined on controller

I'm declaring an instance variable on a Rails Controller and I'm printing its value on a View

def controller_action
    @some_data = "some value"
end

Then we know we can print its value on a view

<p>Some data has <%= @some_data %></p>

My problem is when doing mistakes on a view like this:

<p>Some data has <%= @somedata %></p>

Ruby won't complain and it's difficult to find those mistakes. This also applies for team development where some programmer can create an instance variable on a controller with one name and another programmer expects to print it on a view but accidentally uses other name.

Error when input cd C:

So I'm reading "Ruby Wizardry" by Eric Weinstein and I'm up to the script part and when I input: cd C:\Users\Ender\ruby, Ruby responds with "SyntaxError: <irb>:7: syntax error, unexpected $undefined cd C:\Users\Ender\ruby" What's the syntax error? I input everything as the book said. I have Ruby 2.0.0-p645. Can anyone help, I would appreciate it! BTW, I have .rb files on standby ready for reading and the file exists. The proper command is Dir.chdir DIRECTORY.

How to display error messages in a multi-model form with transaction?

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.

The problem I'm experiencing is: When submitting invalid information for the user, it renders the form again, as it should, but the error messages (such as "username can't be blank") are not displayed. The form does work when valid information is submitted and it does display error messages for organization, just not for user.

How should I adjust the code below so that also the error messages for user get displayed?

def new
  @organization = Organization.new
  @user = @organization.users.build
end

def create
  @organization = Organization.new(new_params.except(:users_attributes))
  #Validations require the organization to be saved before user, as user requires an organization_id. That's why users_attributs are above excluded and why below it's managed in a transaction that rollbacks if either organization or user is invalid. This works as desired.

  @organization.transaction do
    if @organization.valid?
        @organization.save
        begin
          @organization.users.create!(users_attributes)
        rescue
          # Should I perhaps add some line here that adds the users errors to the memory?
          raise ActiveRecord::Rollback
        end
     end
  end

  if @organization.persisted?
    flash[:success] = "Yeah!"
    redirect_to root_url
  else
    @user = @organization.users.build(users_attributes) # Otherwise the filled in information for user is gone (fields for user are then empty)
    render :new
  end

end

The form view includes:

<%= form_for @organization, url: next_url do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <%= f.text_field :name %>
        # Other fields

    <%= f.fields_for :users do |p| %>
        <%= p.email_field :email %>
            # Other fields
    <% end %>

    <%= f.submit "Submit" %>
<% end %>

The error messages partial is as follows:

<% object.errors.full_messages.each do |msg| %>
  <li><%= msg.html_safe %></li>
<% end %>

How to load asset gems only for precompile on heroku?

Rails 4.1+, so there isn't built-in support for an :assets group

I want to keep Heroku's precompile on push behaviour, but don't want the asset gems loaded by the rails server. We don't use any kind of inline coffeescript or scss template rendering in the app, only in the assets, so it's just wasted memory at runtime.

I've played around with extending the rake task, configuring sprocket-rails, and even changing application.js to application.js.erb and adding things like

//= <% require 'jquery-rails' %> 
//= require 'jquery'

but still get these errors:

Sprockets::FileNotFound: couldn't find file 'jquery'

If I keep the asset gems in the default Gemfile group everything works fine.

The point here is to not have them loaded in the production environment, but to have

RAILS_ENV=production rake assets:precompile task 

load them before it executes (and fails because of missing libraries)

How to translate a Ruby regex to JavaScript?

In Ruby I have a regex to get a string formatted like "@xxx":

(/(?<!\S)@[A-Za-z0-9\-]+/)

I also need this regex on the client side, but JavaScript can't read this.

How can I change this regex to JavaScript?

Why is my AJAX request failing?

I'm trying to learn to use AJAX with Rails.

Here is my client side coffeescript code:

$(document).ready ->
  $("#url").blur ->
    $.get("/test_url?url=" + $(this).val(), (data) ->
      alert("Response code: " + data)
    ).fail( () ->
      alert("Why am I failing?")
    )

Here is my server-side Ruby code:

  def url_response
    url = URI.parse(params[:url])
    Net::HTTP.get_response(url).code unless url.port.nil?
  end

The Ruby code is being called and correctly returns the HTTP response code, but I can't do anything with the data because the client-side script says the call has failed. As far as I can see, it is not failing. url_response is being called and it is returning a value, so what exactly is failing here?

samedi 9 mai 2015

Wordpress website mobilw-menu main points doesn't link to sites

I have a problem with the mobile menu on my wordpress website. It's this site: http://ift.tt/1zSZ4mu

If you make your viewport smaller, so that the mobile navigation button shows up, you can click it and the mobile menu shows up.

My problem is following: If I click on the main points in the navigation (like IT-Service, Reparatur or Unternehmen) nothing happens. But I would this main points like to open the sites, which are liked to them. In the Desktop Navigation it works perfect. If I click on "Reparatur", http://ift.tt/1EXv7Ar this links opens, if I click on IT-Service, http://ift.tt/1zSZ4mw this link opens, and so on... On mobile nothing happens if I click them.

I modified the navigation like to display all of the links of the navigation at the same time. Prior the sublinks showed up in a dropdown, if i clicked on one of the mainpoints, but i didn't want this "feature".

So I know, that there is a javascript, that handles that but I don't know which one it is or what I have to change to make the main points link to their pages.

Maybe one of you guys can help me?

Greetings, Linda

issue with WP-API authentication

I have a wordpress page from which I am trying to create a post using the WP AJAX REST API. My expectation is that if the user is already logged in the auth cookie will be in place and I'll be able to do the AJAX POST with the user's context. Yet I'm getting an error that the user is not authorized. What am I missing? Thanks

How to get specific entries from a custom taxonomy? [on hold]

Using a wordpress based website, I have a custom taxonomy "authors" in which I enter the names of publications authors. In this field I usually enter multiple authors' names such as "Mark Twain, Isabelle Lagard, Sandra Cruize".

What I need exactly is:

  1. PHP code by which I can display only the first author in one place at the front end. This means that i need to show the first author (e.g. Mark Twain) only without the tow others.
  2. PHP code by which I can display only the second author in another place at the front end.This means that i need to show the second author (e.g. Isabelle Lagard) only without the tow others.
  3. PHP code by which I can display only the first author in another place at the front end.This means that i need to show the third author (e.g. Sandra Cruize) only without the tow others. etc...

So, what do I have to do please?

How to move Wordpress comments only from one domain to another?

We have a bit of situation here. We have a website (let's say it is www.oldsite.com) where we had more than 2000 posts. There arose a need whereby we had to move some 60-70 posts from this oldsite.com to another domain of ours (www.newsite.com)

So, here is what we did:

  1. Move those 60-70 posts manually from oldsite.com to newsite.com Did a 301 redirect of each of those 60-70 posts from oldsite.com to newsite.com. Google has now started to rank the posts from the newsite.com for this. That's all good till now.
  2. Now, here comes the situation. We also want to move the comments from some of those posts from oldsite.com (some 10-12 posts out of those 60-70) to the respective posts of newsite.com.

How do we do that? Do note that we are pretty comfortable with databases and to some extent PHP. Please help.

Thanks.

Note: We did ask this question on a couple of other forums as well and on WP @ SO but were not able to get any help

Shalin

Show different home page based on user role in WordPress

I've got three home pages: 1. home 2. home-student 3. home-teacher

Based on their custom user role (student, teacher or not logged in) I would like to show a different homepage. My knowledge of PHP is pretty basic, so I'm hoping for an easy answer (or line of code I could paste in my child theme). Many thanks!

Malwares and worms on wordpress

I have CentOS 6 64bit server. I always found a lots of worms and malwares on hosted wordpress websites. I dont know where they are coming.

Examples of worms and malwares:

Php.Trojan.StopPost
Php.Malware.Mailbot

I run scan with ClamAV and remove the codes or the files and they always back.

Please help me, Thank you!

Choosing the right web hosting service

I need some help with choosing the right type of hosting service.

I want to run a WordPress site with about 5000 articles and over 50 authors. The site is expected to be visited by more than 40 000 people a day.

Are the following parameters of hosting enough?:

Max. number od PHP proccesses: 5;
MySQL size: 1 GB;
PHP memory_limit: 128 MB;
PHP upload_max_filesize: 32 MB;
PHP post_max_size: 32 MB

I definitely need the site to work without problems, with no one experiencing 503 or such.

Thank you for helping

iOS Safari Whitepage

I've some problem with a Wordpress (4.2.2) page on multiple iOS devices and I don't know how to troubleshoot it without a debugging tool...

If I load a new site via a link, it loads a white page... Then, after reopen safari and reload the page, it is displayed correctly (only reloading doesn't help).

What I tried: - disable all caching pluging / cleared browser-cache - checked chrome's debugging console... no errors - disable permalinks - disable all plugins

I think it's a JS problem, but I don't know how to localize this problem... Someone has an idea? Many thanks!

Regards,

archive-{post_type}.php breaking when slug is changed

So I have a custom post type called 'events' which is all working fine provided that the slug is the same as the custom post type name. i.e. http://ift.tt/1RnRsh1. Wordpress leverages the archive-events.php nicely

The problem however is if I change the page hierarchy to http://ift.tt/1ciAlNb . Now Wordpress no longer uses the archive-events.php

Could the issue be in the re-write rules? I've tried several changes but nothing seems to resolve this. Here's the code:

//* Add Events post type...
$event_labels = array( 
    'name'                  => _x( 'Events', 'Post Type General Name', 'events' ),
    'singular_name'         => _x( 'Event', 'Post Type Singular Name', 'events' ),
    'all_items'             => __( 'All Events', 'events' ),
    'add_new'               => __( 'Add New', 'events' ),
    'add_new_item'          => __( 'Add New Event', 'events' ),
    'edit_item'             => __( 'Edit Event', 'events' ),
    'new_item'              => __( 'New Event', 'events' ),
    'view_item'             => __( 'View Event', 'events' ),
    'search_items'          => __( 'Search Events', 'events' ),
    'not_found'             => __( 'No Event found', 'events' ),
    'not_found_in_trash'    => __( 'No Events found in Trash', 'events' ),
    'parent_item_colon'     => __( 'Parent Event:', 'events' ),
    'menu_name'             => __( 'Events', 'events' ),
);

$event_args = array( 
    'labels'                => $event_labels,
    'hierarchical'          => false,
    'description'           => 'Events.',
    'supports'              => array( 'title', 'editor', 'thumbnail' ),
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_icon'             => 'dashicons-calendar',
    'menu_position'         => 5,
    'show_in_nav_menus'     => true,
    'publicly_queryable'    => true,
    'exclude_from_search'   => false,
    'has_archive'           => true,
    'query_var'             => 'events',
    'can_export'            => true,
    'rewrite'               => array( 
        'slug'              => 'news/events', 
        'with_front'        => true,
        'feeds'             => true,
        'pages'             => true
    ),
    'capability_type' => 'post'
);

register_post_type( 'events', $event_args );

Any suggestions would be appreciated!!

Is this a plugin ? " Follow Insta "

how're you ? I just wanted to know if follow insta in the footer is a plugin or kind of codes ?

My Cheers bye :3

Sticky div to top of screen when scrolled

I have a Wordpress site with a Jumbotron, inside is a div 'sticky' which is positioned:absolute to the bottom. The jumbotron has a fixed height and I would like the div to 'stick' to the top of the screen when scrolled to.

I have seen multiple threads/examples on the subject but none seem to work for me (most not written in a format that works with/for Wordpress)

What is the best approach to making it work in WP (using function.php, etc)

HTML

<div class="row col-md-12">
 <div class="jumbotron">
    <div class="sticky"><p>CURRENT WORK</p></div>
 </div>
</div><!-- /row -->

CSS

.jumbotron {
  margin: 0;
  width: 100%;
  height: 400px;
  background-color: #fff;
}

.sticky {
  position: absolute;
  bottom: 0; right: 0;
  background-color: red;
  padding: 0 5px;
  width: 200px;
  text-align: center;
}

Insert empty values to wordpress database

I have my form like this:

<div id="titlewrap">
    <label class="" id="title-prompt-text" for="title">Enter title here</label>
    <input type="text" name="title" size="30" value="" id="title" autocomplete="off">
</div>
<br class="clear">
<?php
    $mva_content = '';
    $editor_id = 'editor';
    $settings = array('media_buttons' => false);
    wp_editor($mva_content, $editor_id, $settings);
?>

If I show html source code with CTRL+U it looks like this:

<form action="admin.php?page=list" method="post">
    <div id="poststuff">
        <div id="post-body">
            <div id="post-body-content">
                <div id="titlediv">
                    <div id="titlewrap">
                        <label class="" id="title-prompt-text" for="title">Enter title here</label>
                        <input type="text" name="title" size="30" value="" id="title" autocomplete="off">
                    </div>
                    <br class="clear">
                    <div id="wp-editor-wrap" class="wp-core-ui wp-editor-wrap html-active"><link rel='stylesheet' id='editor-buttons-css'  href='http://localhost/plug/wp-includes/css/editor.min.css?ver=4.0.5' type='text/css' media='all' />
<div id="wp-editor-editor-tools" class="wp-editor-tools hide-if-no-js"><div class="wp-editor-tabs"><a id="editor-html" class="wp-switch-editor switch-html" onclick="switchEditors.switchto(this);">Text</a>
<a id="editor-tmce" class="wp-switch-editor switch-tmce" onclick="switchEditors.switchto(this);">Visual</a>
</div>
</div>
<div id="wp-editor-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="20" autocomplete="off" cols="40" name="editor" id="editor"></textarea></div>
</div>

                    <p class="submit">
                        <input type="submit" name="create" id="create" class="button button-primary" value="Add New Video Ad">
                    </p>
                </div>
            </div>
        </div>
    </div>
</form>

I want to save to my wordpress database after click on a save button:

global $wpdb;
$title = $_POST["title"];
$content = $_POST["editor"];
$wpdb->insert("mytable", array(
   "title" => $title,
   "content" => $content,
)); 

I see that in the database there is a row with incremented id but empty value in title and content columns.

i have tried to put Strings instead of $_POST variables and it works perfectly!

Is there an error with my code?

Wordpress Post Thumbnail Issue

I can see that in my uploads folder all the images I have uploaded into posts have the 4 different sizes.

I have no featured image set for posts but I want to get the thumbnail size to display on my front page.

I have tried putting the_post_thumbnail(); in the loop but nothing is displayed.

Am I missing something? Is there another way to grab a thumbnail size of an image that has been put inside of the post?

Currently I use a catch the image function to grab the first image in the post and display it on the front page with this code, can this be edited to get that thumbnail image?

function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches [1] [0];
    //$first_img = substr($first_img, 0, -4);  

    if(empty($first_img)){ //Defines a default image
    $first_img = bloginfo('template_directory');
    $first_img .= "/images/default.png";
    }
     return $first_img;
}

Thanks

Full Array Being Displayed instead of just data in WP_List_Table

I am getting the following error

Fatal error: Call to undefined function do_meta_boxes() in C:\wordpress\apps\wordpress\htdocs\wp-content\plugins\realtyna\realtyna-plugin.php on line 230

I am using xamp as you can see from error is their anything in xamp i need to set to use this function ?. I am trying to add a simple meta box to display add new form.

add_meta_box('persons_form_meta_box', 'Person data', 'custom_table_example_persons_form_meta_box_handler', 'person', 'normal', 'default');

 <div class="wrap">
    <div class="icon32 icon32-posts-post" id="icon-edit"><br></div>


    <form id="form" method="POST">
         <?php /* NOTICE: here we storing id to determine will be item added or updated */ ?>
        <input type="hidden" name="id" value="<?php echo $item['id'] ?>"/>

        <div class="metabox-holder" id="poststuff">
            <div id="post-body">
                <div id="post-body-content">
                    <?php /* And here we call our custom meta box */ ?>
                    <?php do_meta_boxes('person', 'normal', $item); ?>
                    <input type="submit" value="<?php _e('Save', 'custom_table_example')?>" id="submit" class="button-primary" name="submit">
                </div>
            </div>
        </div>
    </form>
</div>

Strict Standards: Non-static method RCCWP_Options::Get()

I am getting this error in wordpress after migration.

Strict Standards: Non-static method RCCWP_Options::Get() should not be called statically in subdomains/ie/httpdocs/wp-content/plugins/magic-fields/Main.php on line 183

Any idea on how to resolve this error?

New post outside wordpress via XML-RPC with "Send Trackback To" field

I want to create new post on my wordpress blog via XML-RPC.

Problem: I want to send Trackback URLs along with new post, just like we put URLs in wordpress panel (space separated) in Send Trackback to input box:

enter image description here

My code until now is:

$content = array( 
    'title'=>$title, 
    'description'=>$body, 
    'mt_allow_comments'=>0, // 1 to allow comments 
    'mt_allow_pings'=>0, // 1 to allow trackbacks 
    'post_type'=>'post', 
    'mt_keywords'=>$keywords, 
    'categories'=>array($category),
    'wp_post_thumbnail' =>  $thumbnail_id 
); 

Woocommerce(wordpress) email type displaying 'plain/text' instead of 'text/html'

The Woocommerce email settings for all the orders are showing 'Plain text' as Email type, it should show HTML/Multipart too, but it is restricting or overriding to Plain Text. How can we have the options of HTML/Multipart.

I have added a function below to functions.php

function wps_set_content_type(){ return "text/html";enter code here } add_filter( 'wp_mail_content_type','wps_set_content_type' );

but this does not works

WordPress: Can I batch upload lots of files (e.g. via a custom field) which will appear on my website as a list of downloadable files?

TL;DR: Can I upload hundreds of files via WordPress (vanilla or with free/premium plugins) which will appear on my website as downloadable files, or would another CMS be better suited to this task?

More info: I'm building a site to replace an old WordPress MU site. My (non-technical) client needs to be able to create a single profile page for each of their employees. Each employee page must include some or all of:

  • A header image
  • A text intro
  • A photo gallery
  • A list of links
  • Multiple audio embeds
  • Multiple video embeds
  • A list of ~1000 downloadable files, mostly pdf/jpg, divided into subgroups

Ideally the last point would be achieved something like this:

  1. Client adds a custom field and must name it
  2. Client drags any number (realistically 1-100) of files onto the field, or uploads via "add files" function
  3. Files are saved in the backend to a folder named after the custom field
  4. File order is editable by client
  5. The field is output to the HTML page like this:
<h1>Custom Field Name</h1>
<ul>
  <li><a>file1.pdf</a></li>
  <li><a>file2.jpg</a></li>
  ...~100
</ul>

Employee A is totally separate from Employee B, C, etc. All employees' pages will be managed by a single user. Their files should exist separately in the backend. The paths to their files will ideally include their name, but only the filename itself needs to be printed to the page. A file system like this would be perfect:

/EmployeeFirstName-EmployeeLastName/Media/YYYY/Filename.xxx

I believe WP's default media file save directories can be customised via plugins.

I'm trying to do this in WP because it's what I've used in the past and it's what my client is familiar with. A friend recommended the Advanced Custom Fields plugin for WP, which I am looking into. I'm an experienced designer but a beginner developer. I accept my naïveté and I'm keen to learn.

Possible structures:

  • A single WP install with a Page per employee
  • A Multisite WP install with a Site per employee
  • Other?

After much searching I'm beginning to think WP might not be a suitable platform for long and busy pages (~80 video embeds per page, added via ACF) with this type of file management requirement. The admin page for my test page is already very slow to update and I haven't even started the file list part.

Since the key feature of this page template will be the ability to list hundreds of downloadable files, it seems logical to me to pick a CMS based on that requirement, rather than pick a familiar CMS and try to force it to do what I want.

Thanks for reading!

How to Get query vars for an special permalink in wordpress

Hi how can i retrieve query_vars from a permalink without sending user to that page.

actually i need to get query vars for an special permalink while i am in another page or post.

prase_request(); or ... ?>

What function is in charge of keeping wordpress shortcodes between switching views?

I changed core files (until I find the way to re-define the functions with some sort of plugin) to render divs instead of DL's for captions in TinyMCE's js file "wpeditimage.js" and now when I switch back from visual to text view, the image is taken out the caption shortcode. The caption is put after the image every time I switch views.

I thought it would be some selector or regex still looking for a dl, and not finding it… but I don't even know what function is in charge of that matching/syncing.

I changed successfully the php code to render the front end code, but here I'm trying to accomplish the editor to render different code, in the editor (which uses JS, not PHP)

Thanks.

Fetch several rss feeds from other blogs in one page

I am trying to make a function which take an rss fedd URL and fetches the most recent 2 posts. I have tried to remake the snippet from here to a full function in funtions.php as following. I don't want to use a plugin for this since the plugins I have looked at have been close to impossible to style with my own html...

function fetch_feed_from_blogg($path) {
$rss = fetch_feed($path);

if (!is_wp_error( $rss ) ) : 

    $maxitems = $rss->get_item_quantity(2); 
    $rss_items = $rss->get_items(0, $maxitems); 
endif;

function get_first_image_url($html)
    {
      if (preg_match('/<img.+?src="(.+?)"/', $html, $matches)) {
      return $matches[1];
      }
    }

function shorten($string, $length) 
{
    $suffix = '&hellip;';

    $short_desc = trim(str_replace(array("/r", "/n", "/t"), ' ', strip_tags($string)));
        $desc = trim(substr($short_desc, 0, $length));
        $lastchar = substr($desc, -1, 1);
          if ($lastchar == '.' || $lastchar == '!' || $lastchar == '?') $suffix='';
              $desc .= $suffix;
        return $desc;
}

    if ($maxitems == 0) echo '<li>No items.</li>';
    else 
    foreach ( $rss_items as $item ) :

$html = '<ul class="rss-items" id="wow-feed"> <li class="item"> <span class="rss-image"><img src="' .get_first_image_url($item->get_content()). '"/></span>
        <span class="data"><h5><a href="' . esc_url( $item->get_permalink() ) . '" title="' . esc_html( $item->get_title() ) . '"' . esc_html( $item->get_title() ) . '</a></h5></li></ul>';

   return $html;
}

I am also trying to make it so that it can be used several times on a single page.

How to display most viewed posts in custom post type

I'm using keremiya theme for wordpress. I was trying to display my most viewed post in my custom post type if "most_viewed" option is on. The name of my custom post type is watch. How can i do this with my current code? I am also using a plugin called wp-post views to display the views in my sidebar. Here is my query.

    <?php if(get_option('most_viewed') == 'On'): ?>
    <div class="sidebar-right">
    <h2><?php echo get_option('my_title'); ?></h2>
    <div class="fimanaortala">
    <?php $tavsayi = get_option('keremiya_tavsiyesayi'); $tavkat = get_option('keremiya_tavsiyekat');?>
    <?php query_posts('showposts='.$tavsayi.'&v_orderby=desc&cat='.$tavkat.'') ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <div class="filmana">
        <div class="filmsol">
        <?php keremiya_resim('80px', '70px', 'izlenen-resim'); ?>
        </div>
        <div class="filmsag">
            <div class="filmsagbaslik">
            <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
            </div>
            <div class="filmsagicerik">
            <?php if(function_exists('the_views')) { the_views(); echo " "; } ?>
            <p><?php nezaman_yazildi(); ?></p>
            </div>
            <div class="filmizleme">
            <a href="<?php the_permalink() ?>"><img src="<?php bloginfo('template_directory'); ?>/images/filmizle.png" alt="film izle" height="21" width="61" /></a>
            </div>
        </div>
    </div>
    <?php endwhile; else: ?>
    <?php endif; ?>
    <?php wp_reset_query(); ?>
    </div>
</div>

register js for more than one predefined by id pages in script-calls.php

I have this js code (saved as shomz.js file)

var shown = true;
var parent = document.querySelector('.parent');
var child = document.querySelector('.child');

parent.addEventListener('mouseenter', function(){
  child.style.opacity = shown ? 0 : 1;
  shown = !shown;
});

The js is related to the following css

* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 100%;
  margin: 10px auto;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
  transition: opacity 0.5s linear;
}


p {
  padding: 1em;
}

and html:

<div class="parent">
<img src="http://ift.tt/1aOoXsp" alt="" width="500px" height="auto" />

<div class="child">
<img src="http://ift.tt/1HWhQs8" alt="" width="500px" height="auto" />

Starting from the below js register procedure (made by Robin) in script-calls.php for a single page by ID, I was wondering what is the best way to tweak the code, in order to define more than one page (2,3,N) also by ID, applying the above shomz.js code. I am not interested to find a global rule that will affect the whole site pages, but only the defined by ID pages;

// Main Scripts
function register_js() {

    if (!is_admin()) {
        $url_prefix = is_ssl() ? 'https:' : 'http:';

        /* Get id of current page*/
        $page_id     = get_queried_object_id();
        /* Compare the desired page's id with the current page's id, if       they match, enqueue shomz*/
        if(YOUR_ID == $page_id){
            wp_register_script('shomz', THB_THEME_ROOT . '/assets/js/plugins/shomz.js', 'jquery', null, TRUE);
            wp_enqueue_script('shomz');
        }
        wp_localize_script( 'app', 'themeajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
    }
}  

Responsive logo - goes under menu bar

i need your help. When site width is resized between 782 to 0 then the logo is removing from it's initial place - under the sticky menu and creates a black line. My site http://goo.gl/uFZydO

Call to undefined function wp_email()

I have a custom product form inquiry create and all of its data are sent through AJAX. The problem is although I included the wp-load.php file for wp functions and pluggable.phpfile for wp_email function, it still show an error:

Fatal Error: Call to undefined function wp_email()

This is my code for inquire.php inside a folder that sends the email inquiry:

require('../wp-load.php');

require('../wp-includes/pluggable.php');

$to = 'email@email.com';
$subject = 'Product Inquiries';
$message = '
    <table width="99%" cellspacing="0" cellpadding="1" border="0" bgcolor="#eaeaea">
        <tbody>
            <tr>
                <td>
                    <table width="100%" cellspacing="0" cellpadding="5" border="0" bgcolor="#ffffff"><tbody>
                        <tr bgcolor="#eaf2fa">
                            <td colspan="2"><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><strong>Name</strong></font></td>
                        </tr>
                        <tr bgcolor="#ffffff">
                            <td width="20">&nbsp;</td>
                            <td><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px">'.$your_name.'</font> </td>
                        </tr>
                        <tr bgcolor="#eaf2fa">
                            <td colspan="2"><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><strong>Email Address</strong></font></td>
                        </tr>
                        <tr bgcolor="#ffffff">
                            <td width="20">&nbsp;</td>
                            <td><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><a target="_blank" href="mailto:'.$your_email.'">'.$your_email.'</a></font> 
                            </td>
                        </tr>
                        <tr bgcolor="#eaf2fa">
                            <td colspan="2"><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><strong>Phone</strong></font></td>
                        </tr>
                        <tr bgcolor="#ffffff">
                            <td width="20">&nbsp;</td>
                            <td><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px">'.$your_phone.'</font> </td></tr>
                            <tr bgcolor="#eaf2fa">
                                <td colspan="2"><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><strong>Product Link</strong></font></td>
                            </tr>
                            <tr bgcolor="#ffffff">
                                <td width="20">&nbsp;</td>
                                <td><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><a target="_blank" href="'.$prod_link.'">'.$prod_name.'</a></font></td>
                            </tr>
                            <tr bgcolor="#eaf2fa">
                                <td colspan="2"><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><strong>Message</strong></font></td>
                            </tr>
                            <tr bgcolor="#ffffff">
                                <td width="20">&nbsp;</td>
                                <td><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px">'.$your_message.'</font> 
                                </td>
                            </tr>
                            <tr bgcolor="#eaf2fa">
                                <td colspan="2"><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px"><strong>Referred By:</strong></font></td>
                            </tr>
                            <tr bgcolor="#ffffff">
                                <td width="20">&nbsp;</td>
                                <td><font style="FONT-FAMILY:sans-serif;FONT-SIZE:12px">'.$referred_by.'</font> 
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>';
wp_email($to,$subject,$message);

Please help guys.. thanks..