syedsibtain
Tue Nov 19 2024
In Ruby,
Furthermore, using
#ruby #rubyonrails
attr_reader
and attr_accessor
are used to create getter and setter methods for class attributes. These are part of a group of methods (attr_*
methods) that make it easier to create getter and setter methods for class attributes.attr_reader
: Creates a getter method, allowing read-only access to an instance variable.
class Person
attr_reader :name
def initialize(name)
@name = name
end
end
person = Person.new("Sibtain")
puts person.name # Outputs: Sibtain
attr_accessor
: Creates both getter and setter methods, allowing read and write access to an instance variable.
class Person
attr_accessor :name
def initialize(name)
@name = name
end
end
person = Person.new("Sibtain")
puts person.name # Outputs: Sibtain
person.name = "John"
puts person.name # Outputs: John
Furthermore, using
attr_reader
and attr_accessor
promotes encapsulation by controlling how the attributes of a class are accessed and modified.#ruby #rubyonrails
amber.srivastava
Thu Nov 14 2024
-------------------------
The
For example, if you have a list of items (like questions, tasks, or other fields) that can be added, removed, or reordered during form submission,
How
•
•
•
•
Example:-
Key Points:
1.
2.
3.
4.
When to use
• Dynamic Forms: When you have a form where the number of fields can change over time, such as adding/removing questions, tasks, team members, etc.
• Nested Fields: When you have an array of objects (e.g., an array of questions, where each question has a
Advantages:
• It reduces the need for manual state management when adding/removing fields.
• It integrates seamlessly with
• It improves performance by avoiding unnecessary re-renders when fields are added or removed.
#CCT1JMA0Z #useForm #react-hook-form
useFieldArray
hook in react-hook-form
-------------------------The
useFieldArray
hook is part of react-hook-form
and is used for handling dynamic fields in forms, such as arrays of inputs that can be added or removed dynamically.For example, if you have a list of items (like questions, tasks, or other fields) that can be added, removed, or reordered during form submission,
useFieldArray
is the ideal solution to manage that dynamic behaviour without manually managing the state of each individual field.How
useFieldArray
works:•
fields
: An array of objects, where each object represents a field in the array.•
append
: A function to add new fields to the array.•
remove
: A function to remove fields from the array.•
update
: A function to update an individual field in the array.Example:-
import { useForm, useFieldArray } from "react-hook-form";
function DynamicForm() {
const { register, control, handleSubmit, formState: { errors } } = useForm({
defaultValues: {
questions: [{ question: "" }],
},
});
// UseFieldArray to handle the questions array dynamically
const { fields, append, remove } = useFieldArray({
control,
name: "questions", // Name of the array in the form's state
});
const onSubmit = (data: any) => {
console.log(data); // Submitting form data with dynamic fields
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((item, index) => (
<div key={item.id}>
<input
{...register(`questions.${index}.question`)} // Register each question dynamically
defaultValue={item.question} // Set default value for each item in the array
/>
{errors.questions?.[index]?.question && (
<span>{errors.questions[index]?.question.message}</span>
)}
<button type="button" onClick={() => remove(index)}>Remove</button>
</div>
))}
<button type="button" onClick={() => append({ question: "" })}>
Add Question
</button>
<button type="submit">Submit</button>
</form>
);
}
Key Points:
1.
name
: The name
prop in useFieldArray
points to the field array in your form state (in this case, questions
).2.
fields
: This array holds the current data of the dynamic fields. Each item corresponds to a field in the form array.3.
append
: This method is used to add a new item to the array. You can pass the new data for the item when appending.4.
remove
: This method is used to remove an item by its index.When to use
useFieldArray
:• Dynamic Forms: When you have a form where the number of fields can change over time, such as adding/removing questions, tasks, team members, etc.
• Nested Fields: When you have an array of objects (e.g., an array of questions, where each question has a
title
and description
).Advantages:
• It reduces the need for manual state management when adding/removing fields.
• It integrates seamlessly with
react-hook-form
to handle validations and form submission.• It improves performance by avoiding unnecessary re-renders when fields are added or removed.
#CCT1JMA0Z #useForm #react-hook-form
ayasha.pandey
Thu Nov 14 2024
Slack's
#slack #api
chat.deleteScheduledMessage
API allows you to delete messages that were scheduled using chat.scheduleMessage
but have not yet been sent.
const response = await slackClient.chat.deleteScheduledMessage({
channel: channelId, {// ID of the channel where the message was scheduled }
scheduled_message_id: scheduledMessageId, {// ID of the scheduled message to delete}
});
#slack #api
nitturu.baba
Thu Nov 14 2024
How to write tests for external APIs?
This can be achieved using the gem "webmock".
Using webmock we will similate the external API call and use mockdata as the response to the APIs.
step1: install the gem "webmock"
step2: add the following lines to rails helper.
step3: create mock data responses for the APIs inside fixtures folder in spec.
member_api_success.json
step4: inside spec create webmock file. Inside webmock create webmock_api.rb file. In this file we will simulate the responses for the API using mock data we have created.
step5: write the test cases for the APIs in requests folder.
#ruby on rails
This can be achieved using the gem "webmock".
Using webmock we will similate the external API call and use mockdata as the response to the APIs.
step1: install the gem "webmock"
step2: add the following lines to rails helper.
require 'webmock/webmock_api.rb'
config.before(:each) do
stub_request(:any, /domain_name/).to_rack(WebmockApi
end
step3: create mock data responses for the APIs inside fixtures folder in spec.
member_api_success.json
# spec/fixtures/member_api_success.json
[
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "123-456-7890",
"membership_type": "Gold",
"status": "active"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane.smith@example.com",
"phone": "987-654-3210",
"membership_type": "Silver",
"status": "inactive"
}
]
step4: inside spec create webmock file. Inside webmock create webmock_api.rb file. In this file we will simulate the responses for the API using mock data we have created.
class WebmockApi
SPEC_FIXTURES_PATH = 'spec/fixtures'.freeze
MEMBERS_SUCCESS = File.read("#{SPEC_FIXTURES_PATH}/members_api_success.json").freeze
POSTS_SUCCESS = File.read("#{SPEC_FIXTURES_PATH}/posts_api_success.json").freeze
ERROR = File.read("#{SPEC_FIXTURES_PATH}/error.json").freeze
def self.call(env)
new.call(env)
end
def call(env)
action = env['REQUEST_METHOD']
path = env['PATH_INFO']
params = env['QUERY_STRING']
case path
when '/external_members_api_path'
params.include?('test_user') ? [ 200, {}, [ MEMBERS_SUCCESS ] ] : [ 500, {}, [ ERROR ] ]
when '/external_post_api_path'
params.include?('new_post') ? [ 200, {}, [ POSTS_SUCCESS ] ] : [ 500, {}, [ ERROR ] ]
end
end
end
step5: write the test cases for the APIs in requests folder.
require 'rails_helper'
require 'webmock/rspec'
RSpec.describe "Members", type: :request do
describe "GET /members_search_path" do
context "when the members API call is successful" do
it "returns member details from the API" do
get "/external_members_api_path", params: { member: "test_user" }
expect(response).to have_http_status(:ok)
user = response.parsed_body["member"]
expect(["id"]).to eq("123456")
expect(user["name"]).to eq("abc")
end
end
context "when the members API call is successful" do
it "returns error message from the API" do
get "/external_members_api_path", params: { member: "unknown_user" }
expect(response).to have_http_status(:ok)
expect(response).to have_http_status(:internal_server_error)
error = response.parsed_body["error"]
expect(error).to eq("Something went wrong")
end
end
end
end
#ruby on rails
amber.srivastava
Thu Nov 07 2024
SEND SLACK MESSAGE AS A THREAD
To send a message as a thread in Slack using the Slack API, we can use the
Here’s how to send a threaded message:
1. Get the
• If you’re replying to a specific message, you’ll need its
2. Send a Threaded Message Using
• Use
Example:-
If we don't have any parent message then,we can first send a message and then use its
#C04A9DMK81E #slack #slackapi #thread
To send a message as a thread in Slack using the Slack API, we can use the
chat.postMessage
method with the thread_ts
parameter. This parameter specifies the timestamp (ts
) of the parent message you want to reply to, creating a thread.Here’s how to send a threaded message:
1. Get the
ts
(timestamp) of the Parent Message• If you’re replying to a specific message, you’ll need its
ts
value. You can retrieve it by fetching messages in the channel, or from the response of a previously sent message.2. Send a Threaded Message Using
thread_ts
• Use
thread_ts
in the chat.postMessage
payload to post your message as a reply in the thread.Example:-
import { WebClient } from "@slack/web-api";
const client = new WebClient("YOUR_SLACK_BOT_TOKEN");
async function sendThreadedMessage(channel: string, parent_ts: string, message: string) {
try {
// Post a new message as a reply in the thread
const response = await client.chat.postMessage({
channel,
text: message,
thread_ts: parent_ts, // This makes it a threaded message
});
} catch (error) {
console.error("Error sending threaded message:", error);
}
}
// Usage example
sendThreadedMessage("C123456789", "1688852910.123456", "This is a reply in the thread.");
If we don't have any parent message then,we can first send a message and then use its
ts
as the thread_ts
for replies:
async function sendMessageWithThread(channel: string, message: string, replyMessage: string) {
try {
// Send the parent message
const parentMessage = await client.chat.postMessage({
channel,
text: message,
});
// Reply to the message in a thread
await client.chat.postMessage({
channel,
text: replyMessage,
thread_ts: parentMessage.ts,
});
} catch (error) {
console.error("Error sending messages:", error);
}
}
// Usage example
sendMessageWithThread("C123456789", "This is the main message", "This is a reply in the thread.");
#C04A9DMK81E #slack #slackapi #thread
satya
Thu Nov 07 2024
When working with Stimulus, it's common to dynamically update DOM elements. While string interpolation works, using HTML
#CU6U0R822 #stimulus #templates
String interpolation
HTML Templates
<template>
elements is a cleaner and more maintainable approach.#CU6U0R822 #stimulus #templates
String interpolation
// In your stimulus controller
updateList() {
this.listTarget.innerHTML = `
<div class="flex gap-2">
<span>${this.name}</span>
<button>Delete</button>
</div>
`
}
HTML Templates
// In your view
<template data-list-target="template">
<div class="flex gap-2">
<span data-placeholder="name"></span>
<button>Delete</button>
</div>
</template>
// In your Stimulus controller
updateList() {
const template = this.templateTarget.content.cloneNode(true)
template.querySelector('[data-placeholder="name"]').textContent = this.name
this.listTarget.appendChild(template)
}
syedsibtain
Thu Nov 07 2024
In a Rails application, we can provide different views and behaviours based on the type of device accessing our application. One of the ways to achieve this is by using the
1. First, determine if the request is coming from a mobile device and set variant in the controller.
2. Now, create mobile-specific views. For example, if we have an
With the variant set, Rails will automatically choose the correct view.
#rubyonrails
set_variant
method along with mobile-specific templates like index.html+mobile
1. First, determine if the request is coming from a mobile device and set variant in the controller.
def set_variant
browser = Browser.new(request.user_agent)
if browser.device.mobile?
request.variant = :mobile
else
request.variant = :desktop
end
end
2. Now, create mobile-specific views. For example, if we have an
index.html.erb
view, we can create a mobile-specific version by adding +mobile
to the filename.
app/views/orders/index.html.erb
app/views/orders/index.html+mobile.erb
With the variant set, Rails will automatically choose the correct view.
#rubyonrails
ayasha.pandey
Wed Nov 06 2024
useFetch
is a Nuxt composable used to fetch data in a server-side or client-side context, ensuring data is fetched before rendering the component. It is primarily used for making HTTP requests and providing a reactive way of managing the fetched data.useAsyncData
is very similar to useFetch, but it allows for fetching data asynchronously, without blocking the server-side rendering process. It's useful when you want to fetch data in a non-blocking way, enabling the page to render without waiting for the data.Key Difference:
•
useFetch
fetches data synchronously during SSR, blocking the rendering process until the data is available.•
useAsyncData
fetches data asynchronously, allowing the page to render without waiting for the data.#fetch #nuxt #useFetch #useAsyncData
nitturu.baba
Mon Nov 04 2024
In Rails, forms can be created in two ways: with a URL (using
But, when to use which?
Form with URL (
This form is used when you specify a URL directly and typically use it for non-resourceful actions or when you don’t have a specific model associated with the form.
The
Form with Model (
This form is bound to an instance of a model, allowing Rails to automatically set the form action (URL) and method (POST or PATCH) based on whether the model is a new record or an existing one.
Rails determines the correct URL and HTTP method based on the record's state:
• New Record: If
• Existing Record: If
The
#ruby on rails
form_with url: ...
) or with a model (using form_with model: ...
).But, when to use which?
Form with URL (
form_with url: ...
)This form is used when you specify a URL directly and typically use it for non-resourceful actions or when you don’t have a specific model associated with the form.
<%= form_with url: some_path, method: :post do |form| %>
<%= form.text_field :some_field %>
<%= form.submit "Submit" %>
<% end %>
The
form_with_url
is suitable for forms that don't map directly to a model, like search forms, login forms, or other custom actions etc.Form with Model (
form_with model: ...
)This form is bound to an instance of a model, allowing Rails to automatically set the form action (URL) and method (POST or PATCH) based on whether the model is a new record or an existing one.
<%= form_with model: @record do |form| %>
<%= form.text_field :name %>
<%= form.submit %>
<% end %>
Rails determines the correct URL and HTTP method based on the record's state:
• New Record: If
@record.new_record?
is true, Rails generates a POST
request to the model’s create
route.• Existing Record: If
@record.persisted?
is true, Rails generates a PATCH
request to update the model’s update
route.The
form_with_model
is suitable for forms that directly interact with a model, such as forms for creating or editing a resource (like User
, Post
, etc.).#ruby on rails
adithya.hebbar
Mon Nov 04 2024
To update a user’s password in
#auth #aws #cognito
AWS Cognito
and set it as permanent, we can use the AWS CLI
with the following admin command:
aws cognito-idp admin-set-user-password \
--user-pool-id <pool-id> \
--username <cognito-username> \
--password <password> \
--permanent
#auth #aws #cognito
Showing 1 to 5 of 71 results