Adding a string in front of a parameter for a form
Your view should have straightforward fields with no magic. We'll use the Form class to do the complicated stuff.
= f.text_field :subject
The method call to post_tickets does not need to receive the params
because the Form object has already been initialized with the params
values. Also, you shouldn't post the ticket, I think, unless the object is valid, right?
def create
@contacts = Form.new(params[:contacts])
if @contacts.valid?
@contacts.post_tickets
flash[:success] = "Message sent! Thank you for contacting us."
redirect_to new_contact_path
else
flash[:alert] = "Please fill in the required fields"
render action: 'new'
end
end
Your Form model should be responsible for modifying the :subject parameter to include the prefix:
class Form
# Some code omitted
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def post_tickets
client.post_tickets({
:whatever_fields => whatever_attribute,
:username => username,
:subject => "Hello from, #{subject}",
:email => email,
:description => description
})
end
end
That way, the Form object has the correct values as submitted by the user, but you've overwritten the posted subject so that it will return the combined string you want, with "Hello from..."
In post_tickets, reference directly the parameters you want to send, via the attributes with which the Form object has been initialized. In the case of subject
, you'll send a combined value instead.
Please note, I've rewritten your initialize to use a more classic attribute setting method.
Thoughts, questions?
Insert a string at a specific index
You could prototype your own splice()
into String.
Polyfill
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* @this {String}
* @param {number} start Index at which to start changing the string.
* @param {number} delCount An integer indicating the number of old chars to remove.
* @param {string} newSubStr The String that is spliced in.
* @return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
Example
String.prototype.splice = function(idx, rem, str) { return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));};
var result = "foo baz".splice(4, 0, "bar ");
document.body.innerHTML = result; // "foo bar baz"
Insert value into a string at a certain position?
You can't modify strings; they're immutable. You can do this instead:
txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);
Insert variable values in the middle of a string
You can use string.Format
:
string template = "Hi We have these flights for you: {0}. Which one do you want";
string data = "A, B, C, D";
string message = string.Format(template, data);
You should load template
from your resource file and data
is your runtime values.
Be careful if you're translating to multiple languages, though: in some cases, you'll need different tokens (the {0}
) in different languages.
PHP - concatenate or directly insert variables in string
Between those two syntaxes, you should really choose the one you prefer :-)
Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.
The result will be the same; and even if there are performance implications, those won't matter 1.
As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:
echo "Welcome $names!";
PHP will interpret your code as if you were trying to use the $names
variable -- which doesn't exist.
- note that it will only work if you use "" not '' for your string.
That day, you'll need to use {}
:
echo "Welcome {$name}s!"
No need to fallback to concatenations.
Also note that your first syntax:
echo "Welcome ".$name."!";
Could probably be optimized, avoiding concatenations, using:
echo "Welcome ", $name, "!";
(But, as I said earlier, this doesn't matter much...)
1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.
Forward GET parameter to next URL
Click Run code snippet below to see a working example.
Instead of passing your results and going to the next step, you can just hide and reveal portions (steps) of the form using JavaScript.
A framework like AngularJS would make this extremely simple to do using declarative directive. But a plain old JavaScript will suffice.
The other advantage to this approach is that you can then POST your form to the web server.
function goTo(step) { var steps = document.querySelectorAll('[step]'), formStep, formStepNo, i; for (i = 0; i < steps.length; i++) { formStep = steps[i]; formStepNo = formStep.getAttribute('step'); if (step == formStepNo) { formStep.style.display = 'block'; } else { formStep.style.display = 'none'; } }}
var step = 1;goTo(step);
function nextStep() { step++; goTo(step);}
function backStep() { step--; goTo(step);}
<form action="example.html" method="POST"> <div step="1"> <p>Step 1</p> <input type="number" name="Machine" id="Machine" placeholder="Machine" /> <button onclick="nextStep()" type="button">Forward</button> </div> <div step="2"> <p>Step 2</p> <input type="string" name="foo" placeholder="foo"/> <button type="button" onclick="backStep()">Back</button> <button type="button" onclick="nextStep()">Forward</button> </div> <div step="3"> <p>Step 3</p> <input type="string" name="bar" placeholder="bar"/> <button type="button" onclick="backStep()">Back</button> <button type="submit">Submit</button> </div></form>
Related Topics
Ruby Net-Ssh Calling Bash Script with Interactive Prompts
Ruby: How to Dynamically Replace Parameters in Native Pg Gem
How to Schedule a Function to Execute at a Future Time
Calling Protected Class Method from Instance Method in Ruby
I Want to Match All Punctuation in My Regexp Except Apostrophes. How to Do That in Ruby
Unexpected =>, Expecting '}' in Rspec Expect
How Does Rails Know My Timezone
Making a Pie-Chart of the User Age in Rails
Heroku_Can't Upgrade to Cedar-14
Slicing of Arrays in Ruby Returns Different Result - Nil VS. Empty Array
How to Make the Say Command Echo a Variable Value in a Script
How to Make the Days of the Month Be Printed According to Each Day (Ex: Su Mo Tu We...Etc)
How to List All Databases with Activerecord